for循环结构是平常运维工做中用的很频繁的循环结构。python
for 变量名 in 循环条件; do command done
这里的“循环条件”能够是一组字符串挥着数字(用空格隔开),也能够是一条命令的执行结果。linux
[root@zlinux-01 shell]# vim for01.sh #! /bin/bash sum=0 for i in `seq 1 5` do echo $i sum=$[$sum+$i] done echo $sum [root@zlinux-01 shell]# sh for01.sh 1 2 3 4 5 15
/etc/
目录下包含单词yum
的目录。[root@zlinux-01 shell]# vim for2.sh #! /bin/bash cd /etc/ for i in `ls /etc/`; do if [ -d $i ]; then ls -ld $i | grep -w 'yum' fi done [root@zlinux-01 shell]# sh for2.sh drwxr-xr-x. 6 root root 100 3月 16 04:04 yum drwxr-xr-x. 2 root root 248 4月 12 14:53 yum.repos.d
while 条件; do command done
# 冒号代替条件 while : ; do command sleep 30 done
[root@zlinux-01 shell]# vim while01.sh #!/bin/bash while : do load=`w|head -1 |awk -F 'load average: ' '{print $2}'| cut -d . -f1` if [ $load -eq 0 ] then python /usr/lib/zabbix/alertscripts/mail.py zxc00@126.com "load is high:$load" "$load" fi sleep 30 done ##python行表示使用邮件脚本发送负载情况,这里为了实验,把load设为等于0,mail.py脚本在以前zabbix实验中设置 #'while :'表示死循环,也能够写成while true,意思是“真” #Attention:awk -F 'load average: '此处指定'load average: '为分隔符,注意冒号后面的空格 #若是不加该空格,过滤出来的结果会带空格,须要在此将空格过滤掉
实验结果:
说明:若是不手动中止该脚本,它会一直循环执行(按Ctrl+c结束),实际环境中配合screen使用。shell
[root@zlinux-01 shell]# vim while02.sh #!/bin/bash while true do read -p "Please input a number:" n if [ -z "$n" ] then echo "You need input some characters!" continue fi n1=`echo $n|sed 's/[-0-9]//g'` if [ -n "$n1" ] then echo "The character must be a number!" continue fi break done echo $n #continue:中断本次while循环后从新开始; #break:表示跳出本层循环,即该while循环结束
break跳出循环
continue结束本次循环
exit退出整个脚本vim
[root@zlinux-01 shell]# vim break.sh #!/bin/bash for i in `seq 1 5` do echo $i if [ $i -eq 3 ] then break #此处课替换continue和exit,执行脚本查看区别 fi echo $i done echo $i