Shell 學習筆記三(條件分支語句)

        在Shell裏常用的條件分支語句有 if else 語句和 case語句。

IF ELSE 語句

基本結構:

    if condition
    then
    command1
    command2
    ...
    commandN
    fi

if else格式

if condition
then
    command1
    command2
    ...
    commandN
else
    command
fi

if else-if else格式

if condition1
then
    command1
elif condition2
    command2
else
    commandN
fi

if else語句經常與test命令結合使用,如下所示:

#! /bin/bash

num1=$((2*3))
num2=$((1+5))
if test $num1 -eq $num2
then
    echo 'The two numbers are equal!'
else
    echo 'The two numbers are not equal!'
fi

Case語句

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

    case 值 in
    模式1)
    command1
    command2
    ...
    commandN
    ;;
    模式2)
    command1
    command2
    ...
    commandN
    ;;
    esac

         case工作方式如上所示。取值後面必須爲單詞in,每一模式必須以右括號結束。取值可以爲變量或常數。匹配發現取值符合某一模式後,其間所有命令開始執行直至 ;;。取值將檢測匹配的每一個模式。一旦模式匹配,則執行完匹配模式相應命令後不再繼續其他模式。如果無一匹配模式,使用星號 * 捕獲該值,再執行後面的命令。

實例:

echo 'Input a number between 1 to 4'
echo 'Your number is:\c'
read aNum
case $aNum in
    1)  
       echo 'You select 1'
    ;;
    2)  
       echo 'You select 2'
    ;;
    3) 
      echo 'You select 3'
    ;;
    4) 
      echo 'You select 4'
    ;;
    *) 
     echo 'You do not select a number between 1 to 4'
    ;;
esac


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