在函数内添加到 Bash 关联数组
Adding to Bash associative arrays inside functions
我正在尝试使用关联数组来解决 Bash 糟糕的函数参数传递问题。我可以声明一个全局关联数组和 read/write,但我想将变量名传递给函数,因为很多时候我想使用具有不同参数块的相同函数。
各种 Stack Overflow 帖子都有读取函数内传递的数组但不写入它以允许 return 值的方法。伪 Bash 我想做的是:
TestFunc() {
local __PARMBLOCK__= # 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 这样的东西吗?
编辑: 找到重复项。这与 this one.
的答案基本相同
您可以为此使用参考变量,请参阅 help declare
:
declare [-aAfFgilnrtux] [-p] [name[=value] ...]
[...]
-n
make NAME
a reference to the variable named by its value
[...]
When used in a function, declare
makes NAME
s local, as with the local
command.
f() {
declare -n paramblock=""
# 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
打印引用数组,因为它只会显示引用。
我正在尝试使用关联数组来解决 Bash 糟糕的函数参数传递问题。我可以声明一个全局关联数组和 read/write,但我想将变量名传递给函数,因为很多时候我想使用具有不同参数块的相同函数。
各种 Stack Overflow 帖子都有读取函数内传递的数组但不写入它以允许 return 值的方法。伪 Bash 我想做的是:
TestFunc() {
local __PARMBLOCK__= # 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 这样的东西吗?
编辑: 找到重复项。这与 this one.
的答案基本相同您可以为此使用参考变量,请参阅 help declare
:
declare [-aAfFgilnrtux] [-p] [name[=value] ...]
[...]
-n
makeNAME
a reference to the variable named by its value
[...]
When used in a function,declare
makesNAME
s local, as with thelocal
command.
f() {
declare -n paramblock=""
# 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
打印引用数组,因为它只会显示引用。