Shell脚本之while read line的用法


Shell脚本之while read line的用法

while read line
do
       …
done < file

read通过输入重定向,把file的第一行所有的内容赋值给变量line,循环体内的命令一般包含对变量line的处理;然后循环处理file的第二行、第三行。。。一直到file的最后一行。还记得while根据其后的命令退出状态来判断是否执行循环体吗?是的,read命令也有退出状态,当它从文件file中读到内容时,退出状态为0,循环继续惊醒;当read从文件中读完最后一行后,下次便没有内容可读了,此时read的退出状态为非0,所以循环才会退出。
案例:

[root@kafka-server01 scripts]# cat /root/scripts/info
192.168.37.131 root 123456
192.168.37.132 root 123456
 
[root@kafka-server01 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@kafka-server01 scripts]# sh 6.sh
-- root -- 192.168.37.131 -- 123456
-- root -- 192.168.37.132 -- 123456

 
另一种也很常见的用法:

command | while read line
do
    …
done

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

案例:

[root@kafka-server01 scripts]# cat /root/scripts/info
192.168.37.131 root 123456
192.168.37.132 root 123456
 
[root@kafka-server01 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@kafka-server01 scripts]# sh 5.sh
-- root -- 192.168.37.131 -- 123456
-- root -- 192.168.37.132 -- 123456

原创文章,作者:wdmbts,如若转载,请注明出处:https://blog.ytso.com/tech/aiops/274131.html

(0)
上一篇 2022年7月13日 19:07
下一篇 2022年7月13日 19:07

相关推荐

发表回复

登录后才能评论