for循環、while循環、break跳出循環、continue結束本次循環、exit退出整個腳本

         for 循環

範圍的符號用 `` 

`seq 範圍` 

blob.png


1.測試腳本:(1加到100)內容:

blob.png

結果:

blob.png


2.遍歷/etc/下的目錄:

內容:

blob.png

結果:

blob.png


for i in `seq 1 3`  == for i  1 2 3

for循環會以空格或回車作爲分隔符

例如:/tmp/下有三個文件 1.txt、2.txt和3 4.txt(3 4.txt是一個文件,3和4之間有空格)

當在命令行中執行:for i in `ls /tmp/` do echo $i  ;done 

結果則會出現四個文件這樣的顯示1.txt、 2.txt、3和4.txt(這是3 4.txt是一個文件卻因爲空格拆分成兩個)




                  while循環

blob.png

1.格式:

while 條件 ;do ...;done

如 (1)while :  (死循環)  do ;done

     (2)while true == while 1 ;do...;done

2.案例當系統負載大於10時,發送一封郵件(每分鐘發送一次)


#!/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" [email protected]

        (或者:/usr/lib/zabbix/alertscripts/mail.py [email protected] "load is high: $load") 

    fi

    sleep 30     //添加時間間斷,沒30秒查一次

done


( load=`w|head -1|awk -F 'load average: ' '{print $2}'|cut -d. -f1`

blob.png

過濾所要所要字符。|sed 's/ //' 把過濾字符前的空格去除

blob.png


3.案例:判斷輸入的內容是否爲數字

blob.png

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

首先要判斷輸入的內容是否爲空,如果爲空則結束本次循環,繼續提醒要輸入內容

然後判斷輸入內容,是否爲數字還是英文字符串,直到輸入的內容是數字纔會結束(跳出)整個流程


            

                break跳出循環

blob.png

 當在腳本中的for或者while的循環中都是可以的。使用break,當條件

滿足時就會直接跳出本層的循環(就是跳出使用了break這層的循環)

blob.png

執行結果

blob.png

在使用if作判斷時,要在條件範圍在[ ]中的左右都要空一格,否則會有

語法錯誤。


                    continue結束本次循環

!!忽略continue之下的代碼,直接進行下一次循環

blob.png

continue 是僅僅的結束滿足條件的那一次過程,之後的命令也是會執行的

執行結果:

blob.png

blob.png


                    exit退出整個腳本

當整個流程運行命令,遇到exit時,直接退出腳本。

blob.png



執行結果:

blob.png




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章