case命令

case命令

Content #

case命令会采用列表格式来检查变量的多个值:

case variable in
pattern1 | pattern2) commands1;;
pattern3) commands2;;
*) default commands;;
esac

case命令会将指定变量与不同模式进行比较。如果变量与模式匹配,那么shell 就会执行为该模式指定的命令。你可以通过竖线运算符在一行中分隔出多个模式。星号会捕获所有与已知模式不匹配的值。

$ 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命令提供了一种更清晰的方法来为变量每个可能的值指定不同的处理选择。

From #

Linux命令行与shell脚本编程大全