shell循環的區別for&while read line

通過一個小測試來區分循環的不同意義

while read line 是一次性將文件信息讀入並賦值給變量line ,while中使用重定向機制,文件中的所有信息都被讀入並重定向給了整個while 語句中的line 變量

for是每次讀取文件中一個以空格爲分割符的字符串

話術借鑑(http://blog.itpub.net/22664653/viewspace-1175858/

文件ip.txt如下:

192.168.50.59 80
192.168.50.60 80
192.168.50.61 80
192.168.50.62 80
192.168.50.63 80

1、for

[root@localhost ~]# for i in `cat ip.txt`;do echo $i ;done
192.168.50.59
80
192.168.50.60
80
192.168.50.61
80
192.168.50.62
80
192.168.50.63
80

2、while read line

[root@localhost ~]# cat ip.txt |while read line;do echo $line;done
192.168.50.59 80
192.168.50.60 80
192.168.50.61 80
192.168.50.62 80
192.168.50.63 80

個人總結:for以空格爲區分的循環單位 while read line以行爲區分循環單位

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章