bash数组给了我不需要的前缀

时间:2015-04-01 23:52:33

标签: arrays linux bash

declare -A script_input=([name]=input [input]=inputs [output]=inputs )
declare -A script_output=([name]=output [input]=outputs [output]=outputs )
declare -a scripts=(script_output script_input )
echo ${script_output[input]}

结果是:

  

输出

我希望从其他代码中获得类似的结果,但我不

script=${scripts[0]}
echo ${script[input]}

现在我

  

script_output

我无法弄明白为什么!

2 个答案:

答案 0 :(得分:0)

您可以通过创造性地使用' eval'来解决这个问题。获取另一个变量引用的任意哈希值。

但如果是我,我会考虑用Perl或Python重写它,在那里我可以拥有哈希和其他奇怪的数据结构。

答案 1 :(得分:0)

你可以这样做,使用bash间接语法:

script=${scripts[0]}[input]
echo ${!script}

请注意,script的值是数组元素的完整“名称”:

$ echo "$script"
script_output[input]

使用bash v4.3,您可以使用nameref来避免这种摆弄:

# Make script a nameref
declare -n script=${scripts[0]}
# Now you can use script as though it were the named array
echo "${script[input]}"
相关问题