読み取るファイルが現在のディレクトリにある test.txt ファイルであると仮定し、内容は以下の通りです:
Google サンプル Taobao
实例 1
#!/bin/bash
while read line
do
echo $line
done < test.txt
while read line
do
echo $line
done < test.txt
実行出力結果は:
Google サンプル Taobao
实例 2
#!/bin/bash
cat test.txt | while read line
do
echo $line
done
cat test.txt | while read line
do
echo $line
done
実行出力結果は:
Google サンプル Taobao
实例 3
for line in `cat test.txt`
do
echo $line
done
do
echo $line
done
実行出力結果は:
Google サンプル Taobao
for の行ごとの読み取りと while の行ごとの読み取りには違いがあります。例:
$ cat test.txt
Google
サンプル
Taobao
$ cat test.txt | while read line; do echo $line; done
Google
サンプル
Taobao
$ for line in $(<test.txt); do echo $line; done
Google
サンプル
Taobao
サンプル
Taobao
$ cat test.txt | while read line; do echo $line; done
サンプル
Taobao
$ for line in $(<test.txt); do echo $line; done
サンプル
Taobao