# 一、while语句结构:条件为真时,执行循环体代码
while 条件
do
循环体
done
# 二、until语法结构:条件为假时,一直执行循环体代码,直到条件变为真
until 条件
do
循环体
done
2、简单示例
[root@openvpn day4]# cat count.sh
#! /bin/bash
count=0
while [ $count -lt 5 ];
do
echo $count
let count++
done
echo "================"
#! /bin/bash
count=0
until [ $count -gt 4 ];
do
echo $count
let count++
done
[root@openvpn]# ./a.sh
0
1
2
3
4
================
0
1
2
3
4
二 、continue与break
1、区别
continue:默认退出本次循环
break:默认退出本层循环
2、示例
[root@openvpn]# cat a.sh
#! /bin/bash
count=0
while [ $count -lt 5 ];
do
if [ $count -eq 4 ];then
break
fi
echo $count
let count++
done
echo "================"
#! /bin/bash
count=0
until [ $count -gt 4 ];
do
if [ $count -eq 4 ];then
let conunt++
continue
fi
echo $count
let count++
done
[root@openvpn]# ./a.sh
0
1
3
================
0
1
3
三 、案例
案例1:监控web页面状态信息, 失败3次, 表示网站出现问题需要进行报警
[root@openvpn day4]# cat url.sh
#!/bin/bash
count=0
url=$1
while true
do
curl $1 &>/dev/null
if [ $? -eq 0 ];then
echo "$1 is ok"
break
else
let count++
fi
echo "false is ${count}"
if [ $count -eq 3 ];then
echo "$1 is down"
break
fi
done
[root@openvpn day4]# ./url.sh http://www.jd.com
http://www.jd.com is ok
[root@openvpn day4]# ./url.sh http://www.jd.col
false is 1
false is 2
false is 3
http://www.jd.col is down
false值等于3代表要进行第4次尝试,证明页面前访问3次均失败