Iterate over two arrays simultaneously in bash

I have two arrays.

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

I want to loop through these two arrays at the same time, i.e. call the command for the first elements of two arrays, then call the same command for the second elements, etc. Pseudocode:

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

How can i do this?

+68
arrays bash loops
Jul 01 '13 at 11:33
source share
4 answers

From anishsane's answer and comments in it, we now know what you want. Here's the same bashier style using a for loop. See the Looping Constructs section of the reference guide . I also use 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 is 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 may also consider this second option. But note that it will not be easy for you to control the order when the fields are displayed in the second possibility (well, this is an associative array, so this is not surprising).

+84
Jul 01 '13 at 17:10
source share

If all arrays are ordered correctly, just go through the index.

 array=( Vietnam Germany Argentina ) array2=( Asia Europe America ) for index in ${!array[*]}; do echo "${array[$index]} is in ${array2[$index]}" done Vietnam is in Asia Germany is in Europe Argentina is in America 
+32
Jan 21 '16 at 16:13
source share

You need a loop over an array and array2

 i=0 while [ $i -lt ${#array[*]} ]; do echo ${array[$i]} is in ${array2[$i]} i=$(( $i + 1)); done Vietnam is in Asia Germany is in Europe Argentina is in America 

Alternatively, you can use this option (without a loop):

 paste <(tr ' ' '\n' <<< ${array[*]}) <(tr ' ' '\n' <<< ${array2[*]}) | sed 's/\t/ is in /' 
+13
Jul 01 '13 at 11:39 on
source share

If the two variables were two lines with multiple lines, like this:

 listA=$(echo -e "Vietnam\nGermany\nArgentina") listB=$(echo -e "Asia\nEurope\nAmerica") 

Then the solution for this case is:

 while read strA <&3 && read strB <&4; do echo "$strA is in $strB" done 3<<<"$listA" 4<<<"$listB" 
0
May 21 '19 at 20:37
source share



All Articles