Bash无限循环示例
时间:2020-01-09 10:37:23 来源:igfitidea点击:
如何在Linux或UNIX等操作系统下的Bash脚本中编写无限循环?
无限循环不过是一系列指令,这些指令可以无休止地循环,这可能是由于循环没有终止条件,有一个永远无法满足的条件,或者是导致循环重新开始的一条指令。
使用while循环的语法如下:
#!/bin/bash while : do echo "Press [CTRL+C] to stop.." sleep 1 done
这是一个将永远打印的循环。
按[CTRL + C]停止...
请注意:
是空命令。
null命令不执行任何操作,并且其退出状态始终设置为true。
您可以修改上述内容以提高可读性:
#!/bin/bash while true do echo "Press [CTRL+C] to stop.." sleep 1 done
单行bash无限while循环语法如下:
while :; do echo 'Hit CTRL+C'; sleep 1; done
或者
while true; do echo 'Hit CTRL+C'; sleep 1; done
for无限循环示例
#!/bin/bash for (( ; ; )) do echo "Pres CTRL+C to stop..." sleep 1 done
我如何退出循环?
当满足某些条件时,可以使用break语句对for或while循环进行转义:
### for loop example ### for (( ; ; )) do echo "Pres CTRL+C to stop..." sleep 1 if (disaster-condition) then break #Abandon the loop. fi done
或者
### while loop example ### while : do echo "Pres CTRL+C to stop..." sleep 1 if (disaster-condition) then break #Abandon the loop. fi done
您还可以使用case语句来使用break语句:
while : do ### add some input and output here ### case $var in yes) do something ;; no) do something ;; quit) break ;; ##Abandon the loop. ease done
例子
一个示例shell脚本演示了无限循环和break语句的实际用法:
#!/bin/bash # Purpose: Display various options to operator using menus # Author: Hyman Gite < Hyman @ theitroad . com > under GPL v2.0+ # -------------------------------------------------------------------------- # capture CTRL+C, CTRL+Z and quit singles using the trap trap '' SIGINT trap '' SIGQUIT trap '' SIGTSTP # display message and pause pause(){ local m="$@" echo "$m" read -p "Press [Enter] key to continue..." key } # set an while : do # show menu clear echo "---------------------------------" echo " M A I N - M E N U" echo "---------------------------------" echo "1. Show current date/time" echo "2. Show what users are doing" echo "3. Show top memory & cpu eating process" echo "4. Show network stats" echo "5. Exit" echo "---------------------------------" read -r -p "Enter your choice [1-5] : " c # take action case $c in 1) pause "$(date)";; 2) w| less;; 3) echo '*** Top 10 Memory eating process:'; ps -auxf | sort -nr -k 4 | head -10; echo; echo '*** Top 10 CPU eating process:';ps -auxf | sort -nr -k 3 | head -10; echo; pause;; 4) netstat -s | less;; 5) break;; *) Pause "Select between 1 to 5 only" esac done