如何通过间接迭代字典

时间:2018-06-06 16:41:01

标签: 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
}

我遇到的最好的是

function gen_items() {
    dict=$1
    tmp="${dict}[@]"
    for key in "${!tmp}"
    do
        echo $key
    done

}

这实际上只从字典中获取值,但我也需要键。

1 个答案:

答案 0 :(得分:1)

使用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

请参阅: