添加到函数内的 Bash 关联数组



我正在尝试使用关联数组作为 Bash 糟糕的函数参数传递的解决方法。我可以声明一个全局关联数组并读取/写入该数组,但我希望将变量名称传递给函数,因为很多时候我想将同一函数与不同的参数块一起使用。

各种堆栈溢出帖子都有读取函数中传递的数组但不写入数组以允许返回值的方法。 因此,我正在尝试做的伪 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这样的东西?

编辑:找到重复项。这和这个答案基本相同。


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

declare [-aAfFgilnrtux] [-p] [name[=value] ...]
[...]
-nNAME引用由其值命名的变量
[...]
在函数中使用时,declare使NAME本地,就像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打印引用的数组,因为这只会显示引用。

最新更新