Unix Shell控制结构—CASE


类似于其他高级程序语言,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

  • 1
  • 2
  • 下一页

相关内容