Bash Iterate Array Examples

www.lautt‮‬uri.com
Bash Iterate Array Examples

To iterate over the values of an array in Bash, you can use the for loop. This loop allows you to run a block of code repeatedly with different values from the array. Here are some examples of how to use the for loop to iterate over the values of an array in Bash:

  1. Basic array iteration:
my_array=(apple banana cherry)

for value in ${my_array[@]}; do
  echo $value
done

In this example, the my_array array is defined with three values: "apple", "banana", and "cherry". The for loop is then used to iterate over the values of the array. On each iteration, the $value variable is used to access the current value of the array, and the echo command is used to print it to the console. This will output the values of the array, with each value on a separate line.

  1. Array iteration with index:
my_array=(apple banana cherry)

for i in "${!my_array[@]}"; do
  echo "$i: ${my_array[$i]}"
done

In this example, the my_array array is defined with three values, just as in the previous example. The for loop is used to iterate over the indexes of the array, instead of the values. The "${!my_array[@]}" syntax is used to expand the array and provide a list of its indexes to the for loop. On each iteration, the $i variable is used to access the current index of the array, and the ${my_array[$i]} syntax is used to access the corresponding value. The echo command is then used to print the index and value together, separated by a colon. This will output the index and value of each element in the array, with each pair on a separate line.

Created Time:2017-10-16 14:38:38  Author:lautturi