Linux shell - case
June 3, 2024About 1 min
有时尝试计算一个变量的值,在一组可能的值中寻找特定值。在这种情形下,不得不写出一长串 if-then-else 语句,就像下面这样:
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 == "roger" ]
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
# Welcome roger
# 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 命令的例子:
case $USER in
rich | roger)
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
# Welcome roger
# Please enjoy your visit.
case 命令提供了一种更清晰的方法来为变量每个可能的值指定不同的处理选择。