一、for循环

for循环结构是日常运维工作中用的很频繁的循环结构。

1、for循环具体格式:

for 变量名 in 循环条件; do
       command
done

这里的“循环条件”可以是一组字符串挥着数字(用空格隔开),也可以是一条命令的执行结果。

2、for循环实例

实例1:计算1到5之和

[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

实例2:列出/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循环

1、while循环格式

格式1:

while 条件; do
        command
done

格式2:死循环

# 冒号代替条件
while : ; do
        command
                sleep 30
done

2、while循环实例

实例1:当系统负载大于10的时候,发送邮件,每隔30秒执行一次

[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 [email protected] "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: '为分隔符,注意冒号后面的空格
#如果不加该空格,过滤出来的结果会带空格,需要在此将空格过滤掉

实验结果:
shell脚本基础(三)_第1张图片
说明:如果不手动停止该脚本,它会一直循环执行(按Ctrl+c结束),实际环境中配合screen使用。

实例2:交互模式下,用户输入一个字符,检测该字符是否符合条件,如:空、非数字、数字。分别对字符做出判断,然后做出不同的回应。

[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用法

break跳出循环
continue结束本次循环
exit退出整个脚本

[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