在Bash中为关联数组设置动态名称

3

我需要在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]}和其他所有可能的组合,但这些都不起作用。我如何访问这些值,而不是硬编码,数组名称和索引都是动态的?感谢您在此提供任何建议。


1
这可能有所帮助:将echo ${$1[$2]}替换为local x="$1[@]"; echo "${!x[$2]}"。查看:如何将变量用作数组名称的一部分 - undefined
这将打印数组中的所有值。我还尝试了 nm=$1; echo ${!nm[$2]}, nm=$1; echo ${!nm[!2]}nm=$1; idx=$2 echo ${!nm[!idx]},现在不再报错,但返回一个空变量。nm=$1; echo ${$nm[$2]} 仍会抛出“错误的替换”。 - undefined
3个回答

2
数组名称和索引一起需要用于间接参数扩展。
echoValue () {
    # $1  array name
    # $2  array index
    t="$1[$2]"
    echo "${!t}"
}

0
在Bash中,声明在函数外部的变量可以被用作全局变量。这意味着你可以从Bash函数内部调用/访问它们,而无需将变量作为参数传递到函数内部。
举个例子:
#!/bin/bash

function setValue() {
  arr1[v1]=55 
}

function echoValue() {  
    echo ${arr1[v2]} 
}

declare -A arr1=( [v1]=12 [v2]=31 )  
setValue 
echoValue

echo ${arr1[*]}

输出结果为:

31
31 55

我建议你看一下这个Bash变量教程

谢谢,但我已经知道了。然而,函数的重点在于不要使用显式名称,因为我想在多个不同的关联数组上调用该函数。上面的示例只是对问题的分解。 - undefined

0

另一种解决方案

function echovalue() { local str str="echo "'$'"{$1""[$2]}" eval $str }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接