您的位置:首页 > 其它

while read line 与 for 区别

2016-03-31 23:36 537 查看
总结一下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 ;
do
n=$(($n+1))
echo $ip
echo $n
done
[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
1
3001
。。。。。。。

10.1.1.14
19
3002
20
[root@hack test]有的人说是echo $IPS会将所有输出当成一个整体通过管道传输给下一个进程所以在一行,当然添加IFS="\n"之后肯定你已经猜到了,后边的这个案例是把IPS添加到文件了,这个while和for的区别更明显,结果自己尝试
[root@hack test]# cat iptest2.sh
#/bin/bash
#IFS="\n"
echo "====while test ===="
while read line
do
echo $line
done < ./ip.log

echo "====for test ===="
for ip in `cat ip.log`;
do
echo $ip
done
[root@hack test]#
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: