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.
|