设为首页 加入收藏

TOP

Unix Shell控制结构—CASE
2014-11-24 08:27:22 来源: 作者: 【 】 浏览:0
Tags: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


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇UNIX Shell循环控制—while 下一篇UNIX Shell控制结构—IF

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Python 数据分析与可 (2025-12-26 21:51:20)
·从零开始学Python之 (2025-12-26 21:51:17)
·超长干货:Python实 (2025-12-26 21:51:14)
·为什么 Java 社区至 (2025-12-26 21:19:10)
·Java多线程阻塞队列 (2025-12-26 21:19:07)