【发布时间】:2016-04-04 19:42:06
【问题描述】:
我正在尝试创建一个带有变量名的关联数组,但遇到了一些麻烦。我可以毫无问题地声明数组,但是当我尝试填充它时出现错误。
这是我的代码:
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 和关联数组的练习脚本。我正在这里测试一些东西,以便在我尝试编写的实际脚本中使用。
【问题讨论】:
-
链接的答案应该可以解决您的问题。你在这里需要一个nameref。没用怎么办?你到底尝试了什么?澄清一下,您将无法直接使用该变量,但您可以为变量中的名称指定一个本地别名。
-
declare -A $name="( [one]=uno [two]=dos [three]=tres )"将声明和定义数组。
标签: arrays bash variables dynamic associative-array