2015-04-01 27 views
0
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

我想不通爲什麼!

+0

'$ script'是一個簡單的字符串var可以持有一個字符串(這恰好是'script_output')。你不能把它當作一個數組,並期望它能夠按照你的想法工作。我不確定間接性是否會起作用:'$ {!script [input]} _(...測試後,它不起作用...)_,但如果不行,你需要重新考慮你的做法。在符號'$ {script [input]}'中,'script'應該是關聯數組的名稱,而不是包含關聯數組名稱的變量。 – 2015-04-02 00:06:17

+0

@JonathanLeffler事實是,我也需要一個for循環! – barej 2015-04-02 00:16:41

+0

@JonathanLeffler你有什麼建議嗎? – barej 2015-04-02 00:18:56

回答

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]}" 
0

您可以通過創造性地使用'eval'來獲取由另一個變量引用的任意哈希值的值。

但是,如果是我,我會考慮用Perl或Python重寫它,我可以有散列和其他奇怪的數據結構。