如何在bash中使用变量名填充关联数组?

时间:2015-12-30 19:45:54

标签: arrays bash variables dynamic associative-array

我正在尝试使用变量名创建一个关联数组并遇到一些麻烦。我可以毫无困难地声明数组,但是当我尝试填充它时,我得到一个错误。

这是我的代码:

ARR_NAME="tali"

makeArray () {
  name=${ARR_NAME}_$1
  echo name: $name
  declare -A $name  #this works fine
  ${name}=( [foo]=bar [baz]=quux [corge]=grault )  #this gives an error (see below)
}

makeArray dev

以下是我收到的错误消息:

./array_test.sh: line 135: syntax error near unexpected token `[one]=uno'
./array_test.sh: line 135: `  ${name}=( [one]=uno [two]=dos [three]=tres )'

我尝试过的其他事情:

$name=( [one]=uno [two]=dos [three]=tres ) #same error message as above

declare -A $name=( [one]=uno [two]=dos [three]=tres ) 
# gives me the following error (basically the same as above):
./array_test.sh: line 134: syntax error near unexpected token `('
./array_test.sh: line 134: `  declare -A $name=( [one]=uno [two]=dos [three]=tres )'

我是bash的新手,并且一直在谷歌搜索任何可能的事情,但到目前为止没有运气。我找到的最接近的答案是this,但它并没有解决我的问题。我正在使用bash 4.3。

注意:这只是我用来了解bash和关联数组的练习脚本。我正在测试这里的东西,以便在我想写的实际脚本中使用。

1 个答案:

答案 0 :(得分:0)

  

declare -A $name="( [one]=uno [two]=dos [three]=tres )"将声明并定义数组。                        - RICI

这是事实,但缺少重要的 -g 选项,以便在makeArray之外访问数组:

  

-g 选项强制执行                 甚至可以在全局范围内创建或修改变量                 当声明在shell函数中执行时。

所以它是

  declare -gA $name="( [foo]=bar [baz]=quux [corge]=grault )"