**
CASE分支
**
Case多分支位置语句
语法:
-----------------------------------------------------------
case 变量名 in
赋值 )
command1
command2
......
;;
赋值)
command1
command2
......
;;
赋值)
command1
command2
......
;;
*)
command1
command2
......
;;
esac
格式:
--------------------------------------------------------------------
#!/bin/bash
read -p "提示信息:" 变量名
case $变量名 in
[a-z]|[A-Z] ) 模式1
echo "wang." 匹配值1
;; 模式结束
[1-9] ) 模式2
echo "ming." 匹配值2
;; 模式结束
wang|long) 模式3
echo “wml” 匹配值3
;;
*) 默认模式
echo "wang, ming,long" 匹配值
esac 结束
解析:
------------------------------------------------------------------------------------------------------------------------------------
case :为变量匹配值
in :写入
) :模式结束
[0-9]) :表示模式中,可以输入0到9,会显示相应值
A|B) :表示模式中,可以输入A或B,才会显示相应值
;; :表示命令序列的结束
*) :表示默认模式,只要不输入上几个模式所规定的范围,任何字符都可以输入找到匹配值回显
esac :表示结束匹配
举例:
-----------------------------------------------------------
[root@node1 ~]# vim a.sh
#!/bin/bash
case $1 in
a)
cat /etc/passwd | grep ^root ;;
b)
ls /var/log/ ;;
c)
systemctl status iptables.service ;;
*)
echo "this is no" ;;
esac
[root@node1 ~]# cat hgn.sh
#!/bin/bash
read -p "please input a|b|c|d|e : " lc
case $lc in
a)
df -h
;;
b)
free -m
;;
c)
ifconfig
;;
d)
ps -ef
;;
e)
cat /etc/redhat-release
;;
*)
echo "现在花姑娘好开放啊!!!"
;;
esac
举例
[root@localhost shell]# vim b.sh
--------------------------------------------------
#!/bin/bash
case $1 in
[a-z]|[A-Z])
cat /etc/passwd | grep root;;
[1-9])
ls /var/log;;
wang|long)
touch a{1..2};;
*)
echo "yao shu ru can shu";;
esac
--------------------------------------------------
[root@localhost shell]# chmod +x b.sh
[root@localhost shell]# ./b.sh aa
yao shu ru can shu
[root@localhost shell]# ./b.sh a
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
[root@localhost shell]# ./b.sh 1
anaconda libvirt spooler
audit maillog spooler-20170807
boot.log maillog-20170807 sssd
btmp messages tallylog
chrony messages-20170807 tuned
cron ntpstats vmware-vmsvc.log
cron-20170807 pluto vmware-vmusr.log
cups ppp wpa_supplicant.log
dmesg qemu-ga wtmp
dmesg.old rhsm Xorg.0.log
firewalld sa Xorg.0.log.old
gdm samba Xorg.9.log
glusterfs secure yum.log
httpd secure-20170807
lastlog speech-dispatcher
[root@localhost shell]# ./b.sh wang
[root@localhost shell]# ls
a1 a2 a.sh b.sh wml.txt
[root@localhost shell]#
举例:
[root@localhost shell]# vim b.sh
--------------------------------------------------------
#!/bin/bash
read -p "yang xiao meng bi mei: " yx
case $yx in
[a-z]|[A-Z])
cat /etc/passwd | grep root;;
[1-9])
ls /var/log;;
wang|long)
touch a{1..2};;
*)
echo "yao shu ru can shu";;
esac
--------------------------------------------------------
[root@localhost shell]# ./b.sh
yang xiao meng bi mei: m
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
[root@localhost shell]#
本文详细介绍了 Bash shell 脚本中的 case 语句用法,包括语法格式、命令序列、匹配模式等,并提供了多个实用案例进行演示。
讲师-LINUX-DAY22-SHELL-流程控制CASE&spm=1001.2101.3001.5002&articleId=81529820&d=1&t=3&u=58c20412e0c44e408714b3d986bee4bf)
2万+

被折叠的 条评论
为什么被折叠?



