How to iterate over associative arrays in Bash

pex picture pex · Jun 24, 2010 · Viewed 197.8k times · Source

Based on an associative array in a Bash script, I need to iterate over it to get the key and value.

#!/bin/bash

declare -A array
array[foo]=bar
array[bar]=foo

I actually don't understand how to get the key while using a for-in loop.

Answer

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.

The confusion in the other answer comes from the fact that your question includes "foo" and "bar" for both the keys and the values.