Notes

Associative Arrays in Bash

Edit on GitHub

Bash Scripting
2 minutes

Associative arrays are key/value pairs, like Objects in JavaScript. You can iterate/loop over them.

create (declare) an associative array

This is done with the declare -A

1declare -A foo # declare an array
2declare -A foo bar baz # declare multiple arrays
3declare -A myArray=( [key1]=value1 [key2]=value2 [key3]=value3 ) # Initialise all at once

add values to the array

1foo[key]=value

Note the lack of spaces before and after the equal = sign

iterate over key/value pairs

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:

1for i in "${!array[@]}"
2do
3  echo "key  : $i"
4  echo "value: ${array[$i]}"
5done

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.

Troubleshooting

  • declare: -A: invalid option On macOS, the Bash version is 3.2.57. Bash 3 has no associative arrays, they are supported in Bash 4. You can install Bash 4 with Homebrew brew update && brew install bash
  • extensions_modules[key]: command not found make sure there are no space before and after the equal sign when assign values