How to iterate over associative arrays in Bash?

Method 1:

The keys are accessed using an exclamation point: ${!array[@]}, the values are accessed using ${array[@]}.

You can iterate over the key/value pairs like this:

for i in "${!array[@]}"do  echo "key  : $i"  echo "value: ${array[$i]}"done

Note the use of quotes around the variable in the for statement (plus the use of @ instead of *). This is necessary in case any keys include spaces.

Method 2:

There’s nothing too surprising about associative arrays in bash, they are as you probably expect:

declare -A aaaa[hello]=worldaa[ab]=cd

The -A option declares aa to be an associative array. Assignments are then made by putting the “key” inside the square brackets rather than an array index. You can also assign multiple items at once:

declare -A aaaa=([hello]=world [ab]=cd)

Retrieving values is also as expected:

if [[ ${aa[hello]} == world ]]; then    echo equalfibb=${aa[hello]}