2016-12-01 22 views
1

Bash有一個特殊變量,[email protected],它將所有發送到腳本或函數的參數存儲到數組中。如何將此變量的值存儲到只讀數組中?

說我有一個腳本/home/jason/bourne

#!/bin/bash 

declare -ar Args="[email protected]"; 

運行它拋出這個錯誤:

$ /home/jason/bourne --help memory; 
/home/jason/bourne: line 3: Args: readonly variable 

這是一個語法錯誤,或者這難道不是在bash possilbe?


通過寫這篇文章的一半,我想出瞭解決方案。我認爲這是一個有幫助的問題,所以我會用答案發布。

回答

2

解決方案

"[email protected]"變量存儲爲一個數組,你需要像你會與文字陣列()把它包起來。

#!/bin/bash 

declare -ar Args=("[email protected]"); 

for arg in "${Args[@]}"; do 
    echo "${arg}"; 
done; 

輸出示例:

$ /home/jason/bourne --help memory "quoted phrase"; 
--help 
memory 
quoted phrase 

注:[email protected]應該總是""纏繞。 (此規則可能有例外,但至少應遵循99.9%的時間。)在這種情況下,請使用("[email protected]")而不是([email protected])

說明

要創建在bash從頭文字數組,你可以這樣做:

declare -ar array=("a" "b" "c d"); 

"[email protected]"變量擴展到使用包裹在報價每一串字符串列表。用()包裝這個列表將會把它變成一個bash數組。

declare -ar array=("[email protected]"); 

例如,如果"[email protected]"擴展到"a" "b" "c d",然後("[email protected]")將變得("a" "b" "c d")

"[email protected]" == "a" "b" "c d" 
("[email protected]") == ("a" "b" "c d") 

下面是由側代碼示例的一側。

設置/home/jason/bourne腳本這樣:

#!/bin/bash 

declare -ar array=("[email protected]"); 
for val in "${array[@]}"; do 
    echo "${val}"; 
done; 

將輸出這樣的:

$ /home/jason/bourne "a" "b" "c d"; 
a 
b 
c d 

設置/home/jason/bourne腳本這樣:

#!/bin/bash 

declare -ar array=("a" "b" "c d"); 
for val in "${array[@]}"; do 
    echo "${val}"; 
done; 

將輸出同樣的事情:

$ /home/jason/bourne; 
a 
b 
c d 
+1

請注意'(...)'根本不涉及擴展。 ''$ @「'擴展爲*'(...)'內部的一個單詞序列*,並且'(...)'的內容被賦值爲數組參數的元素。 – chepner

+0

@chepner很好的理解我使用'$ @'而不是''$ @'''的錯誤。我添加了一個註釋來指出,以便其他人不會犯同樣的錯誤。 – GreenRaccoon23