2019-03-10

shell中的case判斷

格式shell

在case程序中,能夠在條件中使用|,表示或的意思, 好比2|3表示valuel能夠是2也能夠是3bash

案例:spa

#!/bin/bashcode

read -p "Please input a number: " n #輸入一個數字賦值給n。blog

if [ -z "$n" ]                                        #若是變量n爲空get

theninput

        echo "Please input a number." #顯示「請輸入一個數字」it

        exit 1                                         #退出腳本for循環

ficlass

n1=`echo $n|sed 's/[0-9]//g'`            #給n1賦值「刪除變量n中所有數字

if [ -n "$n1" ]                                     #若是變量n1不爲空(就是包含數字之外的東西)

then                                                   #就

    echo "Please input a number."     #顯示「請輸入一個數字」

    exit 1                                             #退出腳本

fi

if [ $n -lt 60 ] && [ $n -ge 0 ]             #若是變量n小於60且大於等於0

then                                                    #就

        tag=1                                         #給變量tag賦值爲1

elif [ $n -ge 60 ] && [ $n -lt 80 ]        #不然判斷是否大於等於60且小於80

then                                                     #若是是

        tag=2                                           #給變量tag賦值爲2

elif [ $n -ge 80 ] && [ $n -lt 90 ]         #不然判斷是否大於等於80且小於90

then                                                     #若是是

         tag=3                                          #給變量tag賦值爲3

elif [ $n -ge 90 ] && [ $n -le 100 ]      #不然判斷是否大於等於90且小於等於100

 then                                                     #若是是

          tag=4                                         #給變量tag賦值爲4

else                                                       #不然

          tag=0                                         #給變量tag賦值爲0

fi

case $tag in

        1)                                     #變量tag的值爲1

            echo "not ok" #顯示not ok ;;

        2)                                     #變量tag的值爲2

            echo "ok"                     #顯示ok ;;

        3) echo "ook"

             ;;     

        4) echo "oook"

             ;;

          *)                                      #除了以上狀況外

             echo "The number range is 0-100." #顯示數字的範圍是0-100

             ;;

       esac

shell中的for循環

語法: for 變量名 in 條件; do (命令); done #知足in後的條件退出,不然重複執行do後的命令。

 

#!/bin/bash

sum=0

for i in `seq 1 100`   #記數命令:seq 起點 步長 終點(從起點數到終點,按步長記數。默認爲1) do             sum=$[$sum+$i] #爲sum賦值從0累加1至100

            echo $i #顯示變量i的值

done

echo $sum

文件列表循環

#!/bin/bash

cd /etc/

for a in `ls /etc/`

do

        if [ -d $a ]

        then

                ls -d $a

        fi

done

shell中的while循環

語法 while 條件; do … ; done 案例1

#!/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

案例2 #!/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

相關文章
相關標籤/搜索