Bash: How to Iterate Over Associative Array


Often you may want to iterate over an associative array in Bash.

You can use the following methods to do so:

Method 1: Access Keys of Associative Array

echo "${!my_array[@]}"

This particular example will return all of the keys from the associative array named my_array.

Method 2: Access Values of Associative Array

echo "${my_array[@]}"

This particular example will return all of the values from the associative array named my_array.

Method 3: Access Both Keys and Values of Associative Array

for i in "${!my_array[@]}"
do
  echo "$i: ${my_array[$i]}"
done

This particular example will return each key and value (separated by a colon) from the associative array named my_array.

The following example shows how to use each of these methods in practice.

Example: How to Iterate Over Associative Array in Bash

Suppose that create an associative array named my_array in Bash in which the keys are the names of cities and the values are the names of professional basketball teams in those cities:

declare -A my_array=( [Dallas]=Mavs [Miami]=Heat [Orlando]=Magic )

We can use the following syntax to return all of the keys from this associative array:

echo "${!my_array[@]}"

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

Bash iterate over keys of associate array

We can also use the following syntax to return all of the values from this associative array:

echo "${my_array[@]}"

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

Bash iterate over values of associate array

Lastly, we can use the following syntax to iterate over the associative array and return both the keys and the values:

for i in "${!my_array[@]}"
do
  echo "$i: ${my_array[$i]}"
done

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

Bash iterate over associative array

Notice that this returns each key and value in the associative array.

Feel free to replace the colon ( : ) in the echo statement to instead return the keys and values separated by a different delimiter.

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