Site icon Bytefreaks.net

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

Advertisements

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]}"
done

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

Exit mobile version