如果for
循環自動執行字符串分割,這意味着下面的代碼是不可能的:
# this should be (and currently is!) two lines, not four.
for message in "hello world" "goodbye world"; do
echo "$message"
done
,或者對於一個稍微現實世界的例子,考慮:
shopt -s nullglob
echo "Listing length in lines of files with spaces in their names from My Documents"
for file in "My Documents"/*; do
printf '%s\t%s lines\n' "$file" "$(wc -l <"$file")"
done
echo "Done"
。 ..在這種情況下,執行了字符串拆分的for
循環會將My
視爲單獨的文件名,而不是將文件名保存在一起。
如果你想安全將一個字符串分解成多個元素,使用read -a
,不串分裂:
v='a b c'
read -r -a v_a <<<"$v"
for i in "${v_a[@]}"; do
printf '%s' "$i" | od -b
done
這將正常工作,即使輸入值是字符串分割會Munge時間 - - 例如,考慮v='*'
,其中字符串拆分將用當前目錄中的文件列表替換*
字符。
您爲什麼要*想要它?這意味着你不能在不分割它們的情況下遍歷一個字符串數組;那會很糟糕。 –
...說,一般*字符串分裂*是可怕的,寫得很好的程序不會使用它。 –
也就是說,'echo -n'也是*糟糕的 - 請參閱[相關的POSIX規範](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html),它明確建議使用'而不是(請參閱應用使用和理論部分)。 –