【问题标题】:How can I populate an associative array with a variable name in bash?如何在 bash 中使用变量名填充关联数组?
【发布时间】: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


【解决方案1】:

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

确实如此,但缺少重要的 -g 选项以使数组可以在 makeArray 之外访问:

-g 选项强制 要在全局范围内创建或修改的变量,甚至 当 declare 在 shell 函数中执行时。

原来如此

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

【讨论】:

    猜你喜欢
    • 2015-01-07
    • 2022-07-21
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多