模式匹配:case
=============================================
一、 case 语法结构
模式1)
命令序列1
;;
模式2)
命令序列2
;;
模式3)
命令序列3
;;
*)
无匹配后命令序列
esac
==============================================
案例:配置yum源
#!/bin/bash
#yum config case
yum_server=192.168.43.166
os_version=`cat /etc/redhat-release | awk '{print $4}' | awk -F "." '{print $1"."$2}'`
[ -d /etc/yum.repos.d ] || mkdir /etc/yum.repos.d/bak
mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/bak
case "$os_version" in
7.4)
cat >/etc/yum.repos.d/cemtos7u4.repo << EOF
[centos7u4]
name=centos7u4
baseurl=ftp://$yum_server/centos7u4
gpgcheck=0
EOF
echo "7.4 yum configure.."
;;
6.8)
curl -o /etc/yum.repos.d/centos6u8.repo ftp://$yum_server/centos6u8.repo
;;
*)
echo "error"
esac
=========================================================
案例:简单的模式匹配
确定要继续删除吗 yes/no: “y”
案例:删除用户
read -p "Please input a delete user: " user
id $user &>/dev/null
if [ $? -ne 0 ];then
echo "no such user $user"
exit 1
fi
read -p "Are you sure?[y/n]: " action
case "$action" in
y|Y|yes|YES)
userdel -r $user
echo "$user is delete!"
;;
*)
echo "error"
esac
#if [ "$action" != y ];then
# echo "good!"
# exit
#fi
#userdel -r $user
#echo "$user is delete!"
案例2: 系统管理工具箱
Command action
h --------------显示命令帮助
f --------------显示磁盘分区
d --------------显示磁盘挂载
m --------------查看内存使用
u --------------查看系统负载
q --------------退出程序
#!/bin/bash
#system manage
#v1.0 by yyy 2019-08-21
menu() {
cat <<EOF
#################################
#++++++++++管理系统+++++++++++++#
#===============================#
# h. help #
# f. disk parttion #
# d. filesystem mount #
# m. memory #
# u. system load #
# q. wxit #
#################################
EOF
}
while :
do
read -p "Please input[h for help ]: " action
case "$action" in
h)
menu
;;
f)
fdisk -l
;;
d)
df -hT
;;
m)
free -mh
;;
u)
uptime
;;
q)
exit
;;
*)
echo "error"
esac
done