case循环

格式
     case  变量名 in
        value1)                   当值为这个时
              command  			  执行这个指令
	      ;;
        value2)      				当值为这个时
              command  				执行这个指令
              ;;
        *)  						当值为其他内容时
              commond 				执行这个指令
              ;;
     esac

在case程序中,可以在条件中使用|,表示或的意思, 比如
     2|3)
	command
	;;

实例

#!/bin/bash
read -p "Please input a number: " n
if [ -z "$n" ]
then
    echo "Please input a number."
    exit 1
fi

n1=`echo $n|sed 's/[0-9]//g'`
if [ -n "$n1" ]
then
 echo "Please input a number."
 exit 1
fi

if [ $n -lt 60 ] && [ $n -ge 0 ]
then
    tag=1
elif [ $n -ge 60 ] && [ $n -lt 80 ]
then
    tag=2
elif [ $n -ge 80 ]  && [ $n -lt 90 ]
then
    tag=3
elif [ $n -ge 90 ] && [ $n -le 100 ]
then
    tag=4
else
    tag=0
fi

case $tag in
    1)
	echo "not ok"
        ;;
    2)
        echo "ok"
        ;;
    3)
        echo "ook"
        ;;
    4)
        echo "oook"
        ;;
    *)
        echo "The number range is 0-100."
        ;;
esac

for循环

  • 语法:for 变量名 in 条件;do ...;done
  • 案例
#! /bin/bash
sum=0
for i in `seq 1 100`
do
 sum=$[$sum+$i]
 echo $i
done
echo $sum
  • 文件列表循环
#!/bin/bash

cd /etc/
for a in `ls /etc/`
do
    if [ -d $a ]
    then
	 ls -d $a
    fi
done

while循环

  • 语法 while 条件;do ...;done
  • 案例
    #!/bin/bash
    while :
    do
        load=`w|head -1|awk -F 'load average: ' '{print $2}'|cut -d. -f1`
        if [ $load -gt 10 ]
        then
            top|mail -s "load is high: $load" asldkfls@11.com
        fi
        sleep 30
    done
  •  案例
    #!/bin/bash
    while :
    do
        read -p "Please input a number: " n
        if [ -z "$n" ]
        then
    	echo "you need input sth."
    	continue
        fi
        n1=`echo $n|sed 's/[0-9]//g'`
        if [ -n "$n1" ]
        then
    	echo "you just only input numbers."
            continue
        fi
        break
    done
    echo $n
    
04-09 07:42