以前我習慣寫
for f in $(ls mydir) do ... done
但遇到檔名有含空白時就炸了, 像這樣
$ ls mydir/ | cat a b c $ for f in $(ls mydir); do echo $f; done a b c
解法是設 IFS 這個變數
$ IFS=$'\n' $ for f in $(ls mydir); do echo $f; done a b c unset IFS
也可用這個方式在 shell script 裡做到等同於「字串陣列」
files=$(cat <<EOF 1st line 2nd line 3rd line EOF ) IFS=$'\n' for f in $files do echo $f done unset IFS
最後附上 man bash 裡的說明:
The Internal Field Separator that is used for word splitting after expansion and to split lines into words with the read builtin command. The default value is ``<space><tab><new‐ line>''.
沒有留言:
張貼留言