Iterate over two arrays simultaneously in bash

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 in "${!array[@]}"; 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).

Leave a Comment