How to get all the keys of an associative array in Bash?
There are at least 2 ways to get the keys from an associative array of Bash. Let’s start with an example associative array:
$ declare -A aa
$ aa["foo"]=bar
$ aa["a b"]=c
We can use the @
special index to get all the keys and store them in an array:
$ aakeys=("${!aa[@]}")
The array content is all the keys (note the key “a b” has a space within itself):
$ echo ${aakeys[*]}
foo a b
Another more convenient way to operate on the keys from an associative array is to loop the keys as follows:
$ for key in "${!aa[@]}"; do echo $key; done
foo
a b
The spaces are well handled in the for loop.