你经常会发现自己在尝试计算一个变量的值,在一组可能得值中寻找特定值。在这种情形下,你不得不写出一长串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命令提供了一种更清晰的方法来为变量每个可能的值指定不同的处理选择。