鍍金池/ 教程/ Linux/ Shell case esac 語(yǔ)句
Shell 特殊變量:Shell $0, $#, $*, $@, $?, $$和命令行參數(shù)
Shell 文件包含
Shell 輸入輸出重定向:Shell Here Document,/dev/null
Shell 函數(shù)參數(shù)
Shell 簡(jiǎn)介
Shell printf命令:格式化輸出語(yǔ)句
第一個(gè) Shell 腳本
Shell echo 命令
Shell 運(yùn)算符:Shell 算數(shù)運(yùn)算符、關(guān)系運(yùn)算符、布爾運(yùn)算符、字符串運(yùn)算符等
Shell 數(shù)組:shell 數(shù)組的定義、數(shù)組長(zhǎng)度
Shell until 循環(huán)
Shell if else 語(yǔ)句
Shell 變量:Shell 變量的定義、刪除變量、只讀變量、變量類型
Shell 字符串
Shell 與編譯型語(yǔ)言的差異
Shell 函數(shù):Shell 函數(shù)返回值、刪除函數(shù)、在終端調(diào)用函數(shù)
Shell 替換
Shell case esac 語(yǔ)句
Shell for 循環(huán)
什么時(shí)候使用 Shell
Shell 注釋
幾種常見(jiàn)的 Shell
Shell while 循環(huán)
Shell break 和 continue 命令

Shell case esac 語(yǔ)句

case ... esac 與其他語(yǔ)言中的 switch ... case 語(yǔ)句類似,是一種多分枝選擇結(jié)構(gòu)。

case 語(yǔ)句匹配一個(gè)值或一個(gè)模式,如果匹配成功,執(zhí)行相匹配的命令。case 語(yǔ)句格式如下:

case 值 in
模式1)
    command1
    command2
    command3
    ;;
模式2)
    command1
    command2
    command3
    ;;
*)
    command1
    command2
    command3
    ;;
esac

case 工作方式如上所示。取值后面必須為關(guān)鍵字 in,每一模式必須以右括號(hào)結(jié)束。取值可以為變量或常數(shù)。匹配發(fā)現(xiàn)取值符合某一模式后,其間所有命令開(kāi)始執(zhí)行直至 ;;。;; 與其他語(yǔ)言中的 break 類似,意思是跳到整個(gè) case 語(yǔ)句的最后。

取值將檢測(cè)匹配的每一個(gè)模式。一旦模式匹配,則執(zhí)行完匹配模式相應(yīng)命令后不再繼續(xù)其他模式。如果無(wú)一匹配模式,使用星號(hào) * 捕獲該值,再執(zhí)行后面的命令。

下面的腳本提示輸入1到4,與每一種模式進(jìn)行匹配:

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

輸入不同的內(nèi)容,會(huì)有不同的結(jié)果,例如:

Input a number between 1 to 4
Your number is:3
You select 3

再舉一個(gè)例子:

#!/bin/bash

option="${1}"
case ${option} in
   -f) FILE="${2}"
      echo "File name is $FILE"
      ;;
   -d) DIR="${2}"
      echo "Dir name is $DIR"
      ;;
   *) 
      echo "`basename ${0}`:usage: [-f file] | [-d directory]"
      exit 1 # Command to come out of the program with status 1
      ;;
esac

運(yùn)行結(jié)果:

$./test.sh
test.sh: usage: [ -f filename ] | [ -d directory ]
$ ./test.sh -f index.htm
$ vi test.sh
$ ./test.sh -f index.htm
File name is index.htm
$ ./test.sh -d unix
Dir name is unix
$