在學習Linux shell scripts時,一個最常見的錯誤就是用for(for line in $(cat file.txt) do …)循環逐行讀取文件。下面的例子可以看出這樣做的結果。
文件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.