【问题标题】:Adding to Bash associative arrays inside functions在函数内添加到 Bash 关联数组
【发布时间】:2020-06-09 07:51:22
【问题描述】:

我正在尝试使用关联数组来解决 Bash 糟糕的函数参数传递问题。我可以声明一个全局关联数组并对其进行读/写,但我希望将变量名传递给函数,因为很多时候我想将同一个函数与不同的参数块一起使用。

各种堆栈溢出帖子都有读取函数中传递的数组但不写入它以允许返回值的方法。因此,我正在尝试做的 Pseudo Bash 是:

TestFunc() {
    local __PARMBLOCK__=${1} # Tried ${!1} as well

    # Do something with incoming array

    __PARMBLOCK__[__rc__]+=1 # Error occured
    __PARMBLOCK__[__error__]+="Error in TestFunc"
}

declare -A FUNCPARM

# Populate FUNCPARM
TestFunc FUNCPARM
if [[ ${FUNCPARM[__rc__]} -ne 0 ]]; then
    echo "ERROR : ${FUNCPARM[__error__]}
fi

这种事情可能吗,还是我真的需要放弃 Bash 来使用 Python 之类的东西?

【问题讨论】:

标签: bash function associative-array


【解决方案1】:

编辑:找到了副本。这与this one的答案基本相同。


您可以为此使用引用变量,请参阅help declare

declare [-aAfFgilnrtux] [-p] [name[=value] ...]
[...]
-n 使 NAME 成为对其值命名的变量的引用
[...]
在函数中使用时,declare 使 NAMEs 成为局部变量,与 local 命令一样。

f() {
  declare -n paramblock="$1"
  # example for reading (print all keys and entries)
  paste <(printf %s\\n "${!paramblock[@]}") <(printf %s\\n "${paramblock[@]}")
  # example for writing
  paramblock["key 1"]="changed"
  paramblock["new key"]="new output"
}

示例用法:

$ declare -A a=(["key 1"]="input 1" ["key 2"]="input 2")
$ f a
key 2   input 2
key 1   input 1
$ declare -p a
declare -A a=(["key 2"]="input 2" ["key 1"]="changed" ["new key"]="new output" )

这很好用。到目前为止,与我发现的实际关联数组的唯一区别是,您不能使用 declare -p 打印引用的数组,因为这只会显示引用。

【讨论】:

  • 完美!这正是我一直在寻找的。奇怪的是,在我的 Linux 系统的手册页中,它说“-n”不能应用于数组。我想那只能指非关联数组,否则手册页是错误的!我认为“declare -p”不起作用对我来说不是问题。
  • @JimHudd 起初 "cannot be applied to arrays" 也难倒我。但是,这意味着引用本身不能是数组。不过,引用的变量可以是数组和关联数组。 示例: a=1; b=2; declare -n ref=(a b) 失败。 a=(1 2); declare -n ref=a 工作。
猜你喜欢
  • 1970-01-01
  • 2012-01-09
  • 2013-07-10
  • 2012-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-23
  • 2021-11-27
相关资源
最近更新 更多