case语句
case语句是点名语句,每个分支语句之间是平衡的,在进行判定时,每个分支语句之判定一次,适合于字符匹配。
if else 语句适合在判断时用,if语句每个分支语句之间是有优先级的,在进行判定时,每个语句都要判定一次。
case语句和if语句相比,判定次数少。
- 示例 1
[root@fuwu test]# cat case.sh
#!/bin/bash
case $1 in
student|limin|westos)
echo "Welcome,$1"
;;
*)
echo "Sorry!"
;;
esac
[root@fuwu test]# sh case.sh
Sorry!
[root@fuwu test]# sh case.sh limin
Welcome,limin
[root@fuwu test]# sh case.sh aa
Sorry!
- 示例 2 :交互式例子1
[root@fuwu test]# cat jiaohu.sh
#!/bin/bash
while true
do
echo -e "
\033[31m A 显示主机IP \033[0m
\033[32m B 显示磁盘剩余空间 \033[0m
\033[33m C 显示系统运行时间 \033[0m
\033[34m Q 退出系统 \033[0m
"
read -p "请输入你的选择:" char
case $char in
a|A)
ifconfig eth0 | grep "inet " | awk '{print $2}'
;;
b|B)
df -h | awk 'NR==2{print "剩余空间大小为:"$4}'
;;
c|C)
uptime |awk '{print $3}' | awk -F, '{print $1}' | awk -F: '{print "系统已经运行了"$1"小时"$2"分钟"}'
;;
q|Q)
exit 0
;;
esac
done
- 例3:交互式例子2
#!/bin/bash
while true
do
echo "Please input action:
C:create user
D:delete user
E:exit
"
Action_cmd(){
read -p "Your action:" char
case $char in
C|c)
Create_cmd(){
read -p "Please input username:" username
#read -p "Please input passwd" -s passwd
id $username &> /dev/null &&{
echo "$username is exist"
Create_cmd
}||{
useradd "$username"
read -p "Please input passwd:" -s passwd
echo $passwd | passwd --stdin $username &> /dev/null
echo ""
echo "$username is created!"
}
}
Create_cmd
;;
D|d)
Delete_cmd(){
read -p "Please input you want delete username:" user
id $user &> /dev/null &&{
userdel -r $user
echo "$user delete successuful!!"
}||{
echo "$user not exist!"
Delete_cmd
}
}
Delete_cmd
;;
E|e)
echo "bye~"
exit 0
;;
*)
echo "Please input true action!!!"
Action_cmd
;;
esac
}
Action_cmd
done
结果图