Shell脚本之while read line的用法
while read line
dodone < file
read通过输入重定向,把file的第一行所有的内容赋值给变量line,循环体内的命令一般包含对变量line的处理;然后循环处理file的第二行、第三行。。。一直到file的最后一行。还记得while根据其后的命令退出状态来判断是否执行循环体吗?是的,read命令也有退出状态,当它从文件file中读到内容时,退出状态为0,循环继续惊醒;当read从文件中读完最后一行后,下次便没有内容可读了,此时read的退出状态为非0,所以循环才会退出。
案例:
[root@centos7 scripts]# cat /root/scripts/info
192.168.37.131 root 123456
192.168.37.132 root 123456
 
[root@centos7 scripts]# vim 6.sh
#!/bin/bash
file=/root/scripts/info
while read line;do
    user=$(echo $line | cut -d " " -f 2)
    ip=$(echo $line |cut -d " " -f 1)
    passwd=$(echo $line|cut -d " " -f 3)
    # cmd=$*
    echo "-- $user -- $ip -- $passwd"
done < $file
 
[root@centos7 scripts]# sh 6.sh
-- root -- 192.168.37.131 -- 123456
-- root -- 192.168.37.132 -- 123456
 
另一种也很常见的用法:
command | while read line
dodone

如果你还记得管道的用法,这个结构应该不难理解吧。command命令的输出作为read循环的输入,这种结构长用于处理超过一行的输出,当然awk也很擅长做这种事

案例:

[root@centos7 scripts]# cat /root/scripts/info
192.168.37.131 root 123456
192.168.37.132 root 123456
 
[root@centos7 scripts]# vim 5.sh
#!/bin/bash
file=/root/scripts/info
cat $file|while read line;do
    user=$(echo $line | cut -d " " -f 2)
    ip=$(echo $line |cut -d " " -f 1)
    passwd=$(echo $line|cut -d " " -f 3)
    # cmd=$*
    echo "-- $user -- $ip -- $passwd"
done
 
[root@centos7 scripts]# sh 5.sh
-- root -- 192.168.37.131 -- 123456
-- root -- 192.168.37.132 -- 123456