Shell脚本之case语句

本文通过示例对比了Bash脚本中使用复杂的if-else语句与简洁的case语句来实现用户身份验证的过程。展示了case语句在处理多个条件时的便利性和简洁性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 没有对比,就没有伤害,先来看一下使用else if有多麻烦
[root@foundation8 test]# cat if_complex.sh 
#!/bin/bash
#looking for a possible value

if [ $USER = "student" ];then
    echo "Welcome $USER"
    echo "Please enjoy your visiting!"
elif [ $USER = "Bob" ];then
    echo "Welcome $USER"
    echo "Please enjoy your visiting!"
elif [ $USER = "Alice" ];then
    echo "Welcome $USER"
    echo "Please enjoy your visiting!"
elif [ $USER = "Coco" ];then
    echo "Welcome $USER"
    echo "Please enjoy your visiting!"
else
    echo "Sorry,you're not allowed here."
fi
[root@foundation8 test]# sh if_complex.sh 
Sorry,you're not allowed here.
  • case闪亮登场
[root@foundation8 test]# cat case_better.sh 
#!/bin/bash
#using the case command

case $USER in
    student|Bob|Alice|Coco)
        echo "Welcome $USER"
        echo "Please enjoy your visiting!"
        ;;
    *)
        echo "Sorry,you're not allowed here."
esac
[root@foundation8 test]# sh case_better.sh 
Sorry,you're not allowed here.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值