while 循环
语法 while 条件;do ......;done
举例1
#!/bin/bash
while : # 冒号表示死循环 等同于while true
do
load=w|head -1|awk -F 'load average: ' '{print $2}'|cut -d . -f 1
#将w命令输出第一行,已load average:为分隔符 输出第二段,并将输出内容已“.”为分隔符截取第一段输出,将其赋值给变量load
if [ $load -gt 10 ]
then
/usr/local/sbin/mail.py xxx@qq.com "load high" "$load" #发送邮件
fi
sleep 30
done
案例2
#!/bin/bash
while :
do
read -p "please input a number:" n
if [ -z "$n" ]
then
echo "please input a number:"
continue
fi
n1=echo $n|sed 's/[0-9]//g'
if [ -n "$n1" ]
then
echo "please input a number:"
continue
fi
break
done
echo $n
实现提示用户输入纯数字
break 跳出循环
#!/bin/bash
for i in `seq 1 5`
do
echo $i
if [ $i == 3 ]
then
break
fi
echo $i
done
echo end
输出结果为
1
1
2
2
3
end
continue 结束本次循环,直接进行下一次循环
#!/bin/bash
for i in `seq 1 5`
do
echo $i
if [ $i == 3 ]
then
contiune
fi
echo $i
done
echo end
输出结果为
1
1
2
2
3
4
4
5
5
end
exit 直接退出整个脚本
#!/bin/bash
for i in `seq 1 5`
do
echo $i
if [ $i == 3 ]
then
exit
fi
echo $i
done
echo end
输出结果为
1
1
2
2
3