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?
for the first value in array1 you need to loop through the values in array2 (value1, value2, value3…) for the second value in array1 you need to loop through the values in array2 (value1, value2 value3…) for the third value in array1 you need to loop through the values in array2 (value1, value2 value3…)
There are two ways to iterate over items of array using For loop. The first way is to use the syntax of For loop where the For loop iterates for each element in the array. The second way is to use the For loop that iterates from index=0 to index=array length and access the array element using index in each iteration.
In this approach we first sort both the arrays and then compare each element of the first array with each element of the second array for the possible pair, if it's possible to form a pair, we form the pair and move to check for the next possible pair for the next element of the first array.
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).
If all of the arrays are ordered correctly just pass around 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With