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的无限循环实时的监测系统进程,以保证系统中的关键应用一直处于运行状态。


  1. #!/bin/bash

  2. while true

  3. do

  4. HTTPD_STATUS=`service httpd status| grep running`

  5. if [ -z "$HTTPD_STATUS" ]; then

  6. echo "HTTPD is stopped, try to restart"

  7. service httpd restart

  8. else

  9. echo "HTTPD is running, wait 5 sec until next check"

  10. fi

  11. sleep 5

  12. done