How to get the keys and values of an associative array indirectly in Bash?

百般思念 提交于 2019-12-08 04:28:23

问题


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.



来源:https://stackoverflow.com/questions/26268669/how-to-get-the-keys-and-values-of-an-associative-array-indirectly-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!