How to get the keys and values of an associative a

2019-06-02 22:05发布

问题:

In Bash, given only a variable that contains the name of an associative array,

$ declare -A dict=([abc]=125 [def]=456)
$ dictvar="dict"

how can we retrieve the keys and values of the associative array?

回答1:

In Bash, to get keys of an associative array via indirection, given the name of the array in variable dictvar one can leverage declare or local (original source):

$ declare -a 'keys=("${!'"$dictvar"'[@]}")' # or 'local'

Then, to get the values

$ for key in ${keys[@]}; do
$     value_var="${dictvar}[$key]"
$     echo "$key = ${!value_var}"
$ done

An alternative using eval is suggested in this answer.

According to this answer, in Bash 4.3+ this task is much easier to accomplish thanks to a new declare -n that can "resolve" a variable name into an actual variable.