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

下面执行这个脚本,做两个数字的加法。

sh calculator.sh
 Calculator
1.+
2.-
3.*
4./
Enter your choice :1
Enter the first number:
10
Enter the second number:
20.3
the result is:
30.3
若输入除了1-4之外的数据:

sh calculator.sh
 Calculator
1.+
2.-
3.*
4./
Enter your choice :6
calculator.sh: a simple calculator

--the end--

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值