Bash: How to Iterate Over Two Arrays at Once


Often you may want to iterate over two arrays at once in Bash.

You can use the following syntax to do so:

for i in ${!array1[*]}; do 
  echo "${array1[$i]} ${array2[$i]}"
done

This particular example will iterate over the arrays named array1 and array2 and display the corresponding elements from each array on their own lines, separated by a space.

The following example shows how to use this syntax in practice.

Example: How to Iterate Over Two Arrays at Once in Bash

Suppose that we create an array named array1 that contains the names of various cities and another array named array2 that contains the names of professional basketball teams in those cities:

array1=(Dallas Houston Denver Miami)
array2=(Mavs Rockets Nuggets Heat)

We can use the following syntax to iterate over each array and display the corresponding cities and team names on the same line:

for i in ${!array1[*]}; do 
  echo "${array1[$i]} ${array2[$i]}"
done

The following screenshot shows how to use this syntax in practice:

Bash iterate over two arrays at once

The output displays the corresponding elements from each array on the same line.

Note that you can also specify any other words that you’d like to include in the echo statement within the for statement.

For example, we could use the following syntax to output the city name followed by a description of the team name:

for i in ${!array1[*]}; do 
  echo "${array1[$i]} has the following team: ${array2[$i]}"
done

The following screenshot shows how to use this syntax in practice:

Feel free to use similar syntax to iterate over your own two arrays in Bash.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Split a String into an Array
Bash: How to Remove Last Element from Array
Bash: How to Find Minimum and Maximum Values in Array

Leave a Reply