2017-08-04 73 views
1

我正在嘗試將數組傳遞給shell腳本,如this question中所述。我寫的設計簡單採取一個數組的名字,並打印出數組一個小腳本:是否可以在bash中的命令之前執行數組賦值?

#!/bin/bash 
echo "$1" 
echo "${!1}" 
arrayVar=("${!1}") 
echo "${arrayVar[1]}" 

我聲明數組變量符合運行我的腳本,像這樣:

array=(foo bar test) ./test.sh array[@] 

輸出:

|array[@]   # the bars are only here to force the final blank line 
|(foo bar test) 
| 

似乎array,代替實際上正在陣列的,僅僅是字符串(foo bar test)

即使我修改腳本以直接按名稱而不是間接地通過位置參數回顯array,我也會得到相同的結果。

#!/bin/bash 
echo "$1" 
arrayVar=("${!1}") 
echo $arrayVar 
echo "${arrayVar[1]}" 

echo $array 
echo "${array[1]}" 

輸出:

|array[@]   # the bars are only here to force the final blank line 
|(foo bar test) 
| 
|(foo bar test) 
| 

上午我只是做錯了什麼,還是慶典不是一個命令之前支持數組賦值?

回答

2

目前,bash不支持導出數組。這記錄在man bash中:

數組變量可能尚未導出。

2

似乎沒有支持它。

如果array=(foo bar test) ./test.sh不這樣做(array被導出爲文本字符串'(foo bar test)',然後

array=(foo bar test); export array; ./test.sh 

應該,而事實上,出口後,bash將報告該陣列爲導出陣列(x方式出口) :

$ declare -p array 
declare -ax array='([0]="foo" [1]="bar" [2]="test")' 

但是這原來是一個謊言:

$ env | grep array; echo status=$? 
    status=1 
相關問題