你好,游客 登录 注册 搜索
背景:
阅读新闻

Unix Shell控制结构—CASE

[日期:2013-02-02] 来源:Linux社区  作者:bobo12082119 [字体: ]

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

linux
相关资讯       Unix shell  Shell CASE 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款