第九章 流程控制之while循环
1 语法
#while语句结构:条件为真时,执行循环体代码while 条件do循环体done
2 continue与break
continue:默认退出本次循环break:默认退出本层循环
2.1 案例
#!/bin/bashx=0while (($x < 10))doif (($x == 2));thenlet x++continuefiif (($x == 7));thenbreakfiecho $xlet x++doneecho "================"y=0until (($y == 10))doif (($y == 2));thenlet y++continuefiif (($y == 7));thenbreakfiecho $ylet y++done[root@aliyun test]# ./a.sh013456================013456
3 while循环案例
3.1 案例1:监控web页面状态信息,失败三次,表示网站出现问题需要进行告警
#!/bin/bashtimeout=3fails=0success=0url=$1while truedoecho "=====>$fails"if [ $fails -eq 3 ]thenecho "fails值等于3代表要进行第4次尝试,证明页面前访问3次均失败"breakfiwget --timeout=$timeout --tries=1 http://$url -qif [ $? -ne 0 ]thenlet fails++elseecho "页面访问成功"breakfidone[root@aliyun test]# ./f.sh www.xujun.com.cn=====>0=====>1=====>2=====>3fails值等于3代表要进行第4次尝试,证明页面前访问3次均失败
3.2 案例2:猜数字
# 补充知识方法一: 通过random变量产生随机数 (0-32768)echo $RANDOM方法二: 通过openssl命令产生随机数openssl rand -base64 10方法三: 通过时间信息获取随机数date +%S%N方法四: 通过一个特殊设备文件生成随机数head -c9 /dev/urandom|cksumtr -dc 0-9 < /dev/urandom | head -c8方法五: 利用UUID文件生成随机数cat /proc/sys/kernel/random/uuid# 代码实现[root@local shell]# cat guess_age.sh#!/bin/bashnum=`echo $((RANDOM%100+1))`count=0while :do[ $count -eq 3 ] && echo "猜的次数超过3次,退出" && exitread -p "请输入[1-100]之间的一个数字:" x[[ ! $x =~ ^[0-9]+$ ]] && echo "必须输入数字" && continueif [ $x -gt $num ];thenecho "猜大了"elif [ $x -lt $num ];thenecho "猜小了"elseecho "猜对了"breakfilet count++done
4 while循环小结
1、while循环的特长是执行守护进程以及我们希望循环不退出持续执行的场景,用于频率小于1分钟的循环处理,其他的while循环几乎都可以被我们即将要讲的for循环替代
2、一句话,if、for语句最常用,其次while(守护进程),case(服务启动脚本)
