shell结构化命令——case命令

你经常会发现自己在尝试计算一个变量的值,在一组可能得值中寻找特定值。在这种情形下,你不得不写出一长串if-then-else语句,就像下面这样:

$ cat LongIF.sh
#!/bin/bash
# Using a tedious and long if statement
#
if [ $USER == "rich" ]
then
    echo "Welcome $USER"
    echo "Please enjoy your visit."
elif [ $USER == "barbara" ]
then
    echo "Hi there, $USER"
    echo "We're glad you could join us."
elif [ $USER == "christine" ]
then
    echo "Welcome $USER"
    echo "Please enjoy your visit."
elif [ $USER == "tim" ]
then
    echo "Hi there, $USER"
    echo "We're glad you could join us."
elif [ $USER == "testing" ]
then
    echo "Please log out when done with test."
else
    echo "Sorry, you are not allowed here."
fi
$
$ ./LongIF.sh
Welcome christine
Please enjoy your visit.

elif语句会不断检查if-then,为比较变量寻找特定的值。

有了case命令,就无须再写大量的elif语句来检查同一个变量的值了。case命令会采用列表格式来检查变量的多个值:

case variable in

pattern1 | pattern2)  commands1;;

pattern3)  commands2;;

*)  default  commands;;

esac

case命令会将指定变量与不同模式进行比较。如果变量与模式匹配,那么shell就会执行为该模式指定的命令。你可以通过竖线运算符在一行中分隔出多个模式。星号会捕获所有与已知模式不匹配的值。下面是一个将if-then-else程序转换成使用case命令的例子:

$ cat ShortCase.sh
#!/bin/bash
# Using a short case statement
#
case $USER in
rich | christine)
    echo "Welcome $USER"
    echo "Please enjoy your visit.";;
barbara | tim)
    echo "Hi there, $USER"
    echo "We're glad you could join us.";;
testing)
    echo "Please log out when done with test.";;
*)
    echo "Sorry, you are not allowed here."
esac
$
$ ./ShortCase.sh
Welcome christine
Please enjoy your visit.

case命令提供了一种更清晰的方法来为变量每个可能的值指定不同的处理选择。 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值