【发布时间】:2019-03-18 07:17:06
【问题描述】:
我希望使用变量访问关联数组。这个post 接受的答案中的示例正是我想要的:
$ declare -A FIRST=( [hello]=world [foo]=bar )
$ alias=FIRST
$ echo "${!alias[foo]}"
但是,当使用 bash 4.3.48 或 bash 3.2.57 时,这对我不起作用。 但是,如果我不声明(“declare -A”)数组,它确实有效,即这有效:
$ FIRST[hello]=world
$ FIRST[foo]=bar
$ alias=FIRST
$ echo "${!alias[foo]}"
不声明数组有什么问题吗?
【问题讨论】:
-
有一个大问题:它创建了一个数字索引数组,而不是关联(字符串索引)数组。由于
hello和foo没有定义,FIRST[hello]和FIRST[foo]都等价于FIRST[0]。 -
正如 Gordon 所说,第二个不起作用:
echo "${!alias[foo]}" "${!alias[hello]}"将输出bar bar。world丢失了。
标签: arrays bash associative