標籤:shell bash continue/break/sleep
迴圈控制語句:
continue:提前結束本輪迴圈,而直接進入下一輪迴圈判斷;
while CONDITION1; do
CMD1
...
if CONDITION2; then
continue
fi
CMDn
...
done
樣本:求100以內所有偶數之和;
#!/bin/bash#declare -i evensum=0declare -i i=0while [ $i -le 100 ]; do let i++ if [ $[$i%2] -eq 1 ]; then continue fi let evensum+=$idoneecho "Even sum: $evensum"
break:提前跳出迴圈
while CONDITION1; do
CMD1
...
if CONDITION2; then
break
fi
done
建立死迴圈:
while true; do
迴圈體
done
退出方式:
某個測試條件滿足時,讓迴圈體執行break命令;
樣本:求100以內所奇數之和
#!/bin/bash#declare -i oddsum=0declare -i i=1while true; do let oddsum+=$i let i+=2 if [ $i -gt 100 ]; then break fidone
sleep命令:
- delay for a specified amount of time
sleep NUMBER
練習:每隔3秒鐘到系統上擷取已經登入使用者的使用者的資訊;其中,如果logstash使用者登入了系統,則記錄於日誌中,並退出;
#!/bin/bash#while true; do if who | grep "^logstash\>" &> /dev/null; then break fisleep 3doneecho "$(date +"%F %T") logstash logged on" >> /tmp/users.log使用untill實現#!/bin/bash#until who | grep "^logstash\>" &> /dev/null; dosleep 3doneecho "$(date +"%F %T") logstash logged on" >> /tmp/users.log
本文出自 “汪立明” 部落格,請務必保留此出處http://afterdawn.blog.51cto.com/7503144/1916025
shell指令碼編程之迴圈控制語句(continue/break/sleep)