循环控制语句:
continue:提前结束本轮循环,而直接进入下一轮循环判断;
while CONDITION1; do
CMD1
...
if CONDITION2; then
continue
fi
CMDn
...
done
示例:求100以内所有偶数之和;
#!/bin/bash#declare-ievensum=0declare-ii=0while[$i-le100];doleti++if[$[$i%2]-eq1];thencontinuefiletevensum+=$idoneecho"Evensum:$evensum"
break:提前跳出循环
while CONDITION1; do
CMD1
...
if CONDITION2; then
break
fi
done
创建死循环:
while true; do
循环体
done
退出方式:
某个测试条件满足时,让循环体执行break命令;
示例:求100以内所奇数之和
#!/bin/bash#declare-ioddsum=0declare-ii=1whiletrue;doletoddsum+=$ileti+=2if[$i-gt100];thenbreakfidone
sleep命令:
- delay for a specified amount of time
sleep NUMBER
练习:每隔3秒钟到系统上获取已经登录用户的用户的信息;其中,如果logstash用户登录了系统,则记录于日志中,并退出;
#!/bin/bash#whiletrue;doifwho|grep"^logstash\>"&>/dev/null;thenbreakfisleep3doneecho"$(date+"%F%T")logstashloggedon">>/tmp/users.log使用untill实现#!/bin/bash#untilwho|grep"^logstash\>"&>/dev/null;dosleep3doneecho"$(date+"%F%T")logstashloggedon">>/tmp/users.log