Bash Array – For Loop
To iterate over items of an array in Bash, we can use For loop. There are two ways to iterate over items of array using For loop.
The first way is to use the syntax of For loop where the For loop iterates for each element in the array.
The second way is to use the For loop that iterates from index=0 to index=array length and access the array element using index in each iteration.
For Each Element in Array
In the following script, we take an array arr
with three items, and iterate over the items of this array using For loop with for-each syntax.
Example.sh
arr=( "apple" "banana" "cherry" )
for item in "${arr[@]}"
do
echo $item
done
Output
apple
banana
cherry
Iterate over Array Items using For Loop and Index
We take index and increment it in for loop until array length. During each iteration of the loop, we use the index to access the item in array.
Example.sh
arr=( "apple" "banana" "cherry" )
for (( i=0; i<${#arr[@]}; i++ ));
do
echo ${arr[$i]}
done
Output
apple
banana
cherry
Conclusion
In this Bash Tutorial, we have learnt how to iterate over items of an array using For loop.