解決方案
到"[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
請注意'(...)'根本不涉及擴展。 ''$ @「'擴展爲*'(...)'內部的一個單詞序列*,並且'(...)'的內容被賦值爲數組參數的元素。 – chepner
@chepner很好的理解我使用'$ @'而不是''$ @'''的錯誤。我添加了一個註釋來指出,以便其他人不會犯同樣的錯誤。 – GreenRaccoon23