總結一下while read line 與 for循環的差別(白話)
都是讀取檔案 while read line 以\n為分割符,而for是以空格為分隔符
補充一點就是:for會一行一行的讀取,while read line會一次性讀走 ssh周遊時很明顯
還有一個需要注意的是從windos拿過來的檔案預設行尾都是以\r結尾的,如果不轉換linux/unix下就會以為是一行,是以拿過來需要轉換一下。還有一個參數IFS是設定分割符的,以下是幾個案例:
root@hack test]# cat iptest.sh
#/bin/bash
IPS="10.1.1.10 3001
10.1.1.10 3003
10.1.1.11 3001
10.1.1.11 3002
10.1.1.11 3004
10.1.1.11 3005
10.1.1.13 3002
10.1.1.13 3003
10.1.1.13 3004
10.1.1.14 3002"
echo "====while test ===="
i=0
echo $IPS | while read line
do
echo $(($i+1))
echo $line
done
echo "====for test ===="
n=0
for ip in $IPS ;
n=$(($n+1))
echo $ip
echo $n
[root@hack test]#
結果
[root@hack test]# sh iptest.sh
====while test ====
1
10.1.1.10 3001 10.1.1.10 3003 10.1.1.11 3001 10.1.1.11 3002 10.1.1.11 3004 10.1.1.11 3005 10.1.1.13 3002 10.1.1.13 3003 10.1.1.13 3004 10.1.1.14 3002
====for test ====
10.1.1.10
3001
。。。。。。。
10.1.1.14
19
3002
20
[root@hack test]有的人說是echo $IPS會将所有輸出當成一個整體通過管道傳輸給下一個程序是以在一行,當然添加IFS="\n"之後肯定你已經猜到了,後邊的這個案例是把IPS添加到檔案了,這個while和for的差別更明顯,結果自己嘗試
[root@hack test]# cat iptest2.sh
#IFS="\n"
while read line
echo $line
done < ./ip.log
for ip in `cat ip.log`;
本文轉自 aklaus 51CTO部落格,原文連結:http://blog.51cto.com/aklaus/1759038