Bash: How to iterate over associative array and print all key/value pairs

The values of an associative array are accessed using the following syntax ${ARRAY[@]}.

To access the keys of an associative array in bash you need to use  an exclamation point right before the name of the array: ${!ARRAY[@]}.

To iterate over the key/value pairs you can do something like the following example

# For every key in the associative array..
for KEY in "${!ARRAY[@]}"; do
  # Print the KEY value
  echo "Key: $KEY"
  # Print the VALUE attached to that KEY
  echo "Value: ${ARRAY[$KEY]}"

NOTE: The use of quotes around the array of keys ${!ARRAY[@]} in the for statement (plus the use of @ instead of *) is necessary in case any keys include spaces.

This post is also available in: Greek

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.