106 words
1 minutes
How to loop over an array in Bash

How to loop over an array in Bash#

Looping over an array is a common task in shell scripting. This guide provides a method to loop over an array in a Bash script.

Shell Script#

Here is a Bash script to loop over an array:

#!/bin/bash

array=("element1" "element2" "element3")

for element in "${array[@]}"; do
    echo "$element"
done

Explanation#

  • array=("element1" "element2" "element3"): This line defines an array with three elements.
  • for element in "${array[@]}"; do: This loop iterates over each element in the array.
  • echo "$element": This command prints the current element.

Conclusion#

By using this method, you can easily loop over an array in a Bash script. This can be useful for processing lists of items.


How to loop over an array in Bash
https://zxce3.net/posts/shells/how-to-loop-over-an-array-in-bash/
Author
Memet Zx
Published at
2022-05-10