Accessing and Manipulating Array Elements
Accessing Array Elements
To access an element in an array, you can use the following syntax:
echo ${array_name[index]}
For example:
fruits=(apple banana cherry)
echo ${fruits[0]} ## Output: apple
echo ${fruits[1]} ## Output: banana
echo ${fruits[2]} ## Output: cherry
You can also use the @
symbol to access all elements in the array:
echo ${fruits[@]} ## Output: apple banana cherry
Modifying Array Elements
To modify an element in an array, you can simply assign a new value to the desired index:
fruits[1]=orange
echo ${fruits[@]} ## Output: apple orange cherry
Appending to Arrays
You can append new elements to an array using the following syntax:
array_name+=(new_value1 new_value2 ...)
For example:
fruits+=(pear grape)
echo ${fruits[@]} ## Output: apple orange cherry pear grape
Removing Array Elements
To remove an element from an array, you can use the unset
command:
unset fruits[1]
echo ${fruits[@]} ## Output: apple cherry pear grape
This will remove the element at index 1 (the "orange" element).
Iterating over Arrays
You can use a for
loop to iterate over the elements of an array:
for fruit in "${fruits[@]}"; do
echo "Fruit: $fruit"
done
This will output:
Fruit: apple
Fruit: cherry
Fruit: pear
Fruit: grape
By using the "${fruits[@]}"
syntax, we ensure that the array elements are properly expanded, even if they contain spaces or other special characters.