高級Bash腳本編程(六)筆記 [case-esac ,break,continue]

case-esac

Shell case語句爲多選擇語句。可以用case語句匹配一個值與一個模式,如果匹配成功,執行相匹配的命令。case語句格式如下:

casein
模式1)
    command1
    command2
    ...
    commandN
    ;;
模式2)
    command1
    command2
    ...
    commandN
    ;;
esac
  • 取值後面必須爲單詞in,每一模式必須以右括號結束。取值可以爲變量或常數。匹配發現取值符合某一模式後,其間所有命令開始執行直至 ;;。
  • 取值將檢測匹配的每一個模式。一旦模式匹配,則執行完匹配模式相應命令後不再繼續其他模式。如果無一匹配模式,使用星號 * 捕獲該值,再執行後面的命令。
    下面的腳本提示輸入1到4,與每一種模式進行匹配:
echo 'Enter a number between 1 and 4:'
echo 'The number you entered is:'
read aNum
case $aNum in
    1)  echo 'You have chosen 1'
    ;;
    2)  echo 'You have chosen 2'
    ;;
    3)  echo 'You have chosen 3'
    ;;
    4)  echo 'You have chosen 4'
    ;;
    *)  echo 'You did not enter a number between 1 and 4'
    ;;
esac

輸入不同的內容,會有不同的結果,例如:

Enter a number between 1 and 4:
The number you entered is:
3
You have chosen 3

跳出循環

在循環過程中,有時候需要在未達到循環結束條件時強制跳出循環,Shell使用兩個命令來實現該功能:break和continue。

break命令

break命令允許跳出所有循環(終止執行後面的所有循環)。 下面的例子中,腳本進入死循環直至用戶輸入數字大於5。要跳出這個循環,返回到shell提示符下,需要使用break命令。

#!/bin/bash
while :
do
    echo -n "Enter a number between 1 and 5:"
    read aNum
    case $aNum in
        1|2|3|4|5) echo "The number you entered is $aNum!"
        ;;
        *) echo "The number you entered is not between 1 and 5! game over!"
            break
        ;;
    esac
done

執行以上代碼,輸出結果爲:

Enter a number between 1 and 5:3
The number you entered is 3!
Enter a number between 1 and 5:7
The number you entered is not between 1 and 5! game over!

continue

continue命令與break命令類似,只有一點差別,它不會跳出所有循環,僅僅跳出當前循環。 對上面的例子進行修改:

#!/bin/bash
while :
do
    echo -n "Enter a number between 1 and 5: "
    read aNum
    case $aNum in
        1|2|3|4|5) echo "The number you entered is $aNum!"
        ;;
        *) echo "The number you entered is not between 1 and 5!"
            continue
            echo "game over"
        ;;
    esac
done

運行代碼發現,當輸入大於5的數字時,該例中的循環不會結束,語句 echo “Game is over!” 永遠不會被執行。

esac

case的語法和C family語言差別很大,它需要一個esac(就是case反過來)作爲結束標記,每個case分支用右圓括號,用兩個分號表示break。

發佈了39 篇原創文章 · 獲贊 75 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章