Iterate over two arrays simultaneously in bash

user2354862 picture user2354862 · Jul 1, 2013 · Viewed 67k times · Source

I have two arrays.

array=(
  Vietnam
  Germany
  Argentina
)
array2=(
  Asia
  Europe
  America
)

I want to loop over these two arrays simulataneously, i.e. invoke a command on the first elements of the two arrays, then invoke the same command on the second elements, and so on. Pseudocode:

for c in $(array[*]}
do
  echo -e " $c is in ......"
done

How can i do this?

Answer

gniourf_gniourf picture gniourf_gniourf · Jul 1, 2013

From anishsane's answer and the comments therein we now know what you want. Here's the same thing in a bashier style, using a for loop. See the Looping Constructs section in the reference manual. I'm also using printf instead of echo.

#!/bin/bash

array=( "Vietnam" "Germany" "Argentina" )
array2=( "Asia" "Europe" "America" )

for ((i=0;i<${#array[@]};++i)); do
    printf "%s is in %s\n" "${array[i]}" "${array2[i]}"
done

Another possibility would be to use an associative array:

#!/bin/bash

declare -A continent

continent[Vietnam]=Asia
continent[Germany]=Europe
continent[Argentina]=America

for c in "${!continent[@]}"; do
    printf "%s is in %s\n" "$c" "${continent[$c]}"
done

Depending on what you want to do, you might as well consider this second possibility. But note that you won't easily have control on the order the fields are shown in the second possibility (well, it's an associative array, so it's not really a surprise).