linux中shift break continue 語句用法

來源:互聯網
上載者:User

shift命令聲明格式: shift [n]
    shift命令用來把指令碼的位置參數列表向左移動指定的位元(n),如果shift沒有參數,則將參數列表向左移動一位。一旦移位發生,被移出列表的參數就被永遠刪除了。通常在while迴圈中,shift用來讀取列表中的參數變數。
    見如下樣本指令碼:

 代碼如下 複製代碼

    /> set stephen ann sheryl mark #設定4個參數變數。
    /> shift                                    #向左移動參數列表一次,將stephen移出參數列表。
    /> echo $*
    ann sheryl mark
    /> shift 2                                 #繼續向左移動兩位,將sheryl和ann移出參數列表
    /> echo $*
    mark
    /> shift 2                                 #繼續向左移動兩位,由於參數列表中只有mark了,因此本次移動失敗。
    /> echo $*
    mark
   
    /> cat > test4.sh
    while (( $# > 0 ))                    #等同於 [ $# -gt 0 ]
    do
            echo $*
            shift
    done
    CTRL+D
    /> . ./test4.sh a b c d e
    a b c d e
    b c d e
    c d e
    d e
    e      

  
    
    break命令聲明格式:break [n]
    和C語言不同的是,Shell中break命令攜帶一個參數,即可以指定退出迴圈的層數。如果沒有指定,其行為和C語言一樣,即退出最內層迴圈。如果指定迴圈的層數,則退出指定層數的迴圈體。如果有3層嵌套迴圈,其中最外層的為1,中間的為2,最裡面的是3。
    見如下樣本指令碼:
   

 代碼如下 複製代碼
/> cat > test5.sh
    while true
    do
        echo -n "Are you ready to move on?"
        read answer
        if [[ $answer == [Yy] ]]
        then
                break
        else
                echo "Come on."
        fi
    done
    echo "Here we are."
    CTRL+D
    /> . ./test5.sh
    Are you ready to move on? y
    Here we are

    
    continue命令聲明格式:continue [n]
    和C語言不同的是,Shell中continue命令攜帶一個參數,即可以跳轉到指定層級的迴圈頂部。如果沒有指定,其行為和C語言一樣,即跳轉到最內層迴圈的頂部。如果指定迴圈的層數,則跳轉到指定層級迴圈的頂部。如果有3層嵌套迴圈,其中最外層的為3,中間的為2,最裡面的是1。

 代碼如下 複製代碼

    /> cat  maillist                       #測試資料檔案maillist的內容為以下資訊。
    stephen
    ann
    sheryl
    mark
   
    /> cat > test6.sh
    for name in $(cat maillist)
    do
            if [[ $name == stephen ]]; then
                    continue
            else
                    echo "Hello, $name."
            fi
    done
    CTRL+D
    /> . ./test6.sh
    Hello, ann.
    Hello, sheryl.
    Hello, mark.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.