如何在Bash中间接获取关联数组的键和值? [英] How to get the keys and values of an associative array indirectly in Bash?
问题描述
在Bash中,仅给出一个包含关联数组名称的变量,
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?
推荐答案
在Bash中,要通过间接获取关联数组的键,给定变量dictvar
中的数组名称,则可以利用declare
或
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'
然后,获取值
$ for key in ${keys[@]}; do
$ value_var="${dictvar}[$key]"
$ echo "$key = ${!value_var}"
$ done
在此答案中建议使用eval
的替代方法.
An alternative using eval
is suggested in this answer.
根据此答案,在Bash 4.3+中,由于有了新的declare -n
,此任务更容易实现可以将变量名解析"为实际变量.
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.
这篇关于如何在Bash中间接获取关联数组的键和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!