【问题标题】:How to iterate a dictionary through indirection如何通过间接迭代字典
【发布时间】:2018-06-06 16:41:01
【问题描述】:

我想在 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

}

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

【问题讨论】:

  • 没有namerefs,间接变量构造是你能做的最好的。

标签: bash associative-array


【解决方案1】:

使用名称引用:

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

见:

【讨论】:

  • 我忘了提到我使用的是 GNU bash,版本 4.1.2 并且声明不支持 -n 选项。是的,在 bash 4.4.x 上声明 -n hash=$1 可以正常工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-25
  • 1970-01-01
  • 1970-01-01
  • 2014-04-10
  • 2016-10-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多