15.2.3 while的无限循环
和for循环相比,while的无限循环更为简单明了,主要有如下3种形式的写法。注意由while的无限循环结构本身并无终止循环的结构,所以要想跳出循环必须在循环体中自行判断,并使用循环控制语句break来终止循环(循环控制语句将在15.6小节中讲到)。
#
方法一
while ((1))
do
command
done
#
方法二
while true
do
command
done
方法三
while :
do
command
done
我们可以利用while的无限循环实时的监测系统进程,以保证系统中的关键应用一直处于运行状态。
- #!/bin/bash
while true
do
HTTPD_STATUS=`service httpd status| grep running`
if [ -z "$HTTPD_STATUS" ]; then
echo "HTTPD is stopped, try to restart"
service httpd restart
else
echo "HTTPD is running, wait 5 sec until next check"
fi
sleep 5
done