Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 如何通过间接寻址迭代字典_Bash_Associative Array - Fatal编程技术网

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

我想在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
}
我来过的最好的是

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

见:


我忘了提到我使用的是GNU bash 4.1.2版,declare不支持-n选项。是的,在bash4.4.x上declare-nhash=$1可以正常工作。没有namerefs,间接变量构造是最好的方法。
key=two
key=three
key=one