1.基本语法
while [ 条件表达式 ] do 语句 语句 done
示例:循环输出 1~10这几个数
[root@openeuler ~]# cat while1.sh #!/bin/bash i=1 while [ $i -le 10 ] do echo $i let i++ done
示例:使用 exec 读取指定文件的内容并循环输出。
# 第一步创建文件及内容 [root@openeuler ~]# cat > myfile << eof > open > openlab > openlab123 > linux > readhat > eof [root@openeuler ~]# cat myfile open openlab openlab123 linux readhat # 第二步:编写脚本来实现文件读取并循环输出 [root@openeuler ~]# cat while2.sh #!/bin/bash exec < myfile while read line do echo $line done [root@openeuler ~]# bash while2.sh open openlab openlab123 linux readhat
使用另一种方式来读取文件:
[root@openeuler ~]# cat while3.sh #!/bin/bash while read line do echo $line done < myfile [root@openeuler ~]# bash while3.sh open openlab openlab123 linux readhat
2.无限循环
在 while 的表达式中,可以指定以下几个特殊值:
- true 它会一直循环,而且它的状态返码是 0
- false 它不做任何事,表示成功,状态码为 0
- : 它的作用与 true 相同,都是进行无限循环
示例:
[root@openeuler ~]# while true ; do echo 123123 ; done #会一直循环 [root@openeuler ~]# while false ; do echo 123123 ; done [root@openeuler ~]# echo $? 0 [root@openeuler ~]# while : ; do echo 123123 ; done
3.使用示例
[root@openeuler ~]# cat while4.sh #!/bin/bash price=$[ $random % 100 ] time=0 while true do read -p 'please enter product price [0-99]: ' input let time++ if [ $input -eq $price ]; then echo 'good luck, you guessed it.' echo 'you have guessed $time times.' exit 0 elif [ $input -gt $price ]; then echo "$input is to high" else echo "$input is to low" fi if [ $time -eq 5 ]; then echo "you have guessed is 5 times. exit" exit 1 fi done [root@openeuler ~]# bash while4.sh please enter product price [0-99]: 50 50 is to low please enter product price [0-99]: 80 80 is to high please enter product price [0-99]: 70 70 is to high please enter product price [0-99]: 60 60 is to low please enter product price [0-99]: 65 65 is to low you have guessed is 5 times. exit [root@openeuler ~]#
示例:使用while读取文件
# 1. 创建文件 [root@openeuler ~]# cat ips 192.168.72.131 22 192.168.72.132 23 192.168.72.133 22 # 2. 编写脚本 [root@openeuler ~]# cat while6.sh #!/bin/bash while read line do ip=`echo $line|cut -d" " -f1` # 也可以使用awk来实现,如:ip=`echo $line|awk '{print $1}'` port=$(echo $line|cut -d " " -f 2) echo "ip:$ip, port:${port}" done < ips # 3. 运行测试 [root@openeuler ~]# bash while6.sh ip:192.168.72.131, port:22 ip:192.168.72.132, port:23 ip:192.168.72.133, port:22
到此这篇关于shel while循环的文章就介绍到这了,更多相关shell while循环内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论