Loop through Indices of Array

To loop through indices of array in Bash, use the expression ${!arr[@]} to get the indices and use For loop to iterate over these indices.

Examples

In the following script, we take an array arr with three elements and iterate over the indices of this array.

Example.sh

arr=("apple" "banana" "cherry")

for index in "${!arr[@]}";
do
    echo "$index -> ${arr[$index]}"
done

Output

0 -> apple
1 -> banana
2 -> cherry

Now, let us take an array with indices specified during initialisation, and then loop through the indices of this array.

Example.sh

arr=([2]="apple" [4]="banana" [9]="cherry")

for index in "${!arr[@]}";
do
    echo "$index -> ${arr[$index]}"
done

Output

2 -> apple
4 -> banana
9 -> cherry
ADVERTISEMENT

Conclusion

In this Bash Tutorial, we have learnt how to loop through the indices of an array in Bash shell.