How to Loop Over an Array in Bash
In this tutorial, you will learn how to loop over an array in the Bash shell script. Whether you are a beginner or an experienced Bash developer, iterating over elements in an array is a fundamental skill that you’ll find useful in many situations.
Let’s start with an example array that contains three strings:
1 | list=( "first" "second" "third" ) |
Now, let’s loop over the elements in the list
array:
1 | for i in "${list[@]}" |
In the example above, the for
loop iterates over each element of the array using the "${list[@]}"
syntax. The @
symbol ensures that each element is treated as a separate entity.
Inside the loop, you can perform any desired operations by referencing the current element with the variable i
.
For demonstration purposes, the example script simply echoes each element of the array using the echo
command.
And that’s it! You now know how to loop over an array in the Bash shell script.
Tags: loop, bash, array, shell script