學 Linux shell 腳本時,最常見的錯誤莫過於用 for 迴圈(for line in $(cat file.txt))來逐行讀檔。先看它會產生什麼結果。
假設 file.txt 的內容是:
cat file.txt
This is the row No 1;
This is the row No 2;
This is the row No 3.
用 for 迴圈:
for line in $(cat file.txt); do echo $line; done
This / is / the / row / No / 1; / This / is / the / row / No / 2; / […]
顯然這不是我們想要的——它會以空白為單位把每一行拆碎。正解是改用帶內建讀取的 while 迴圈。
while 迴圈才是逐行讀檔最恰當也最簡單的方法:
while read line; do echo $line; done < file.txt
This is the row No 1;
This is the row No 2;
This is the row No 3.
如此一來,每一行都會被完整、原樣地讀出,正是我們期望的行為。