考慮下面bash中逐漸添加到陣列
#! /bin/bash
declare -a input # unnecessary
declare -a bad
declare -a good # unnecessary
input=('alpha 23' 'bravo 79' 'charlie 12')
echo "input is " ${#input[@]} "long"
for x in "${input[@]}"
do
bad=$x
good[ ${#good[@]} ]=$x
echo
echo "added '$x', good is now " ${#good[@]} "long, bad is still " ${#bad[@]} "long"
done
代碼輸出是
input is 3 long
added 'alpha 23', good is now 1 long, bad is still 1 long
added 'bravo 79', good is now 2 long, bad is still 1 long
added 'charlie 12', good is now 3 long, bad is still 1 long
按照手冊頁對於bash ...「當分配給索引數組,如果提供了可選的括號和下標,該索引被分配給; 否則分配的元素的索引是語句加上一個分配給的最後一個索引,索引從零開始。
我顯然不明白粗體的部分,因爲我期望聲明「bad = $ x」每次執行時自動遞增索引。它不會,並且每次都分配給bad [0]。
爲什麼沒有做什麼,我的預期是有寫代碼比笨拙行,我分配到良好的更好的方法[..]
請參閱:[Bash:添加數值而不指定鍵](http://stackoverflow.com/q/1951506/3 776858) – Cyrus