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/basharray=( "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/bashdeclare -A continentcontinent[Vietnam]=Asiacontinent[Germany]=Europecontinent[Argentina]=Americafor 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).
You need a loop over array & array2
i=0while [ $i -lt ${#array[*]} ]; do echo ${array[$i]} is in ${array2[$i]} i=$(( $i + 1));doneVietnam is in AsiaGermany is in EuropeArgentina is in America
EDIT: Do not use the below tr
based implementation. It will not work for array elements containing spaces. Not removing it so as to keep the comments relevant. See glenn jackman's comment instead of below answer.
/EDIT
Alternately, you can use this option (without loop):
paste <(tr ' ' '\n' <<< ${array[*]}) <(tr ' ' '\n' <<< ${array2[*]}) | sed 's/\t/ is in /'