Shell脚本之while read line的用法
2022/7/14 5:20:32
本文主要是介绍Shell脚本之while read line的用法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Shell脚本之while read line的用法while read line do … done < fileread通过输入重定向,把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
这篇关于Shell脚本之while read line的用法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?