我需要在bash中对几个不同的关联数组执行相同的操作。因此,我想使用函数来避免代码重复。然而,我在访问函数内部数据时遇到了问题。这里是一个简单的示例:
#!/bin/bash
# this function works fine
function setValue() {
# $1 array name
# $2 array index
# $3 new value
declare -g $1[$2]=$3
}
# this function doesn't
function echoValue() {
# $1 array name
# $2 array index
echo ${$1[$2]}
}
declare -A arr1=( [v1]=12 [v2]=31 )
setValue arr1 v1 55
echoValue arr1 v2
我已经尝试过${$1[$2]}, ${!1[!2]}和其他所有可能的组合,但这些都不起作用。我如何访问这些值,而不是硬编码,数组名称和索引都是动态的?感谢您在此提供任何建议。
echo ${$1[$2]}
替换为local x="$1[@]"; echo "${!x[$2]}"
。查看:如何将变量用作数组名称的一部分。 - undefinednm=$1; echo ${!nm[$2]}
,nm=$1; echo ${!nm[!2]}
和nm=$1; idx=$2 echo ${!nm[!idx]}
,现在不再报错,但返回一个空变量。nm=$1; echo ${$nm[$2]}
仍会抛出“错误的替换”。 - undefined