Bash 如何通过间接寻址迭代字典
我想在bash中实现以下伪代码Bash 如何通过间接寻址迭代字典,bash,associative-array,Bash,Associative Array,我想在bash中实现以下伪代码 function gen_items() { dict=$1 # $1 is a name of a dictionary declared globally for key in $dict[@] do echo $key ${dict[$key]} # process the key and its value in the dictionary done } 我来过的最好的是 functi
function gen_items() {
dict=$1 # $1 is a name of a dictionary declared globally
for key in $dict[@]
do
echo $key ${dict[$key]}
# process the key and its value in the dictionary
done
}
我来过的最好的是
function gen_items() {
dict=$1
tmp="${dict}[@]"
for key in "${!tmp}"
do
echo $key
done
}
这实际上只从字典中获取值,但我还需要键。使用nameref:
show_dict() {
((BASH_VERSINFO[0] < 4 || ((BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] < 3)))) &&
{ printf '%s\n' "Need Bash version 4.3 or above" >&2; exit 1; }
declare -n hash=$1
for key in "${!hash[@]}"; do
echo key=$key
done
}
declare -A h
h=([one]=1 [two]=2 [three]=3)
show_dict h
见:
key=two
key=three
key=one