Bash Array – While Loop

To iterate over items of an array in Bash, we can use While loop. In the While loop start with index=0 and execute the loop until index is less than array length. During each iteration we can access the item of array at the index.

Iterate over Array Items using While Loop

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" )

i=0
len=${#arr[@]}
while [ $i -lt $len ];
do
    echo ${arr[$i]}
    let i++
done

Output

apple
banana
cherry
ADVERTISEMENT

Conclusion

In this Bash Tutorial, we have learnt how to iterate over items of an array using While loop.