歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> Unix Shell控制結構—CASE

Unix Shell控制結構—CASE

日期:2017/3/1 10:02:11   编辑:SHELL編程

類似於其他高級程序語言,Shell中case語句的作用也是作為多項選擇使用,語法如下:

case word in
pattern1)
Statement(s) to be execute if pattern1 matchs
;;
pattern2)
Statement(s) to be execute if pattern2 matchs
;;
pattern3)
Statement(s) to be execute if pattern3 matchs
;;
*)
Default action
;;
esac

有一點域其他高級語言中不太一樣的地方,在高級語言中,若每個case後面沒有break語句,

則此判斷將會遍歷所有的case,直至結束;而在shell中,若匹配了某個模式,則執行其中的命令;

執行完後(;;)直接退出此case;若無其他模式匹配輸入,則將執行默認處理默認模式(*)部分。

pattern模式不能包含元字符:*、?、[..](類,如[a-z]等)

pattern模式裡面可以包含或符號(|),表示多個匹配,如y|Y|yes|YES。

下面是一個簡單的例子。

模擬一個計算器,進行+、-、*、/運算

#!/bin/ksh

echo " Calculator"
echo "1.+"
echo "2.-"
echo "3.*"
echo "4./"

echo -n "Enter your choice :"
read I

case $I in
1)
echo "Enter the first number:"
read A
echo "Enter the second number:"
read B
echo "the result is:"
echo " $A + $B " | bc
;;
2)
echo "Enter the second number:"
read A
echo "Enter the second number:"
read B
echo "the result is:"
echo " $A - $B " | bc
;;
3)
echo "Enter the first number:"
read A
echo "Enter the second number:"
read B
echo "the result is:"
echo " $A * $B " | bc
;;
4)
echo "Enter the first number:"
read A
echo "Enter the second number:"
read B
echo "the result is:"
echo " $A / $B " | bc
;;
*)
echo "`basename $0`: a simple calculator"
;;
esac

#EOF

Copyright © Linux教程網 All Rights Reserved