首页 > 代码库 > shell脚本编程之循环控制语句(continue/break/sleep)
shell脚本编程之循环控制语句(continue/break/sleep)
循环控制语句:
continue:提前结束本轮循环,而直接进入下一轮循环判断;
while CONDITION1; do
CMD1
...
if CONDITION2; then
continue
fi
CMDn
...
done
示例:求100以内所有偶数之和;
#!/bin/bash # declare -i evensum=0 declare -i i=0 while [ $i -le 100 ]; do let i++ if [ $[$i%2] -eq 1 ]; then continue fi let evensum+=$i done echo "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=0 declare -i i=1 while true; do let oddsum+=$i let i+=2 if [ $i -gt 100 ]; then break fi done
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 fi sleep 3 done echo "$(date +"%F %T") logstash logged on" >> /tmp/users.log 使用untill实现 #!/bin/bash # until who | grep "^logstash\>" &> /dev/null; do sleep 3 done echo "$(date +"%F %T") logstash logged on" >> /tmp/users.log
本文出自 “汪立明” 博客,请务必保留此出处http://afterdawn.blog.51cto.com/7503144/1916025
shell脚本编程之循环控制语句(continue/break/sleep)