case模式匹配
case 语法结构
一、case 语法结构(字符串比较)
case 变量 in
模式1)
命令序列1
;;
模式2)
命令序列2
;;
模式3)
命令序列3
;;
*)
无匹配后命令序列
esac
示例1
编写脚本,由用户输入字符串,如果输入的字符串为Linux则显示Windows,为Windows则显示Linux,否则显示other
#!/bin/bash
read -p "Input string: " str
case $str in
windows)
echo "Linux..."
;;
linux)
echo "Windows..."
;;
*)
echo "Other...."
;;
esac
示例2
1.根据不同的系统版本,使用 if 配置yum源,
2.快速修改脚本为case
if 语句示例
os_version=`cat /etc/redhat-release | awk '{print $4}'|awk -F"." '{print $1}' `
if [ "$os_version" = "7" ];then
cat > /etc/yum.repos.d/centos7.repo <<-EOF
[centos]
name=centos7
baseurl=ftp://10.18.40.100/centos7u3
gpgcheck=0
EOF
yum makecache
yum repolist
echo "yum Configuration completed"
fi
if [ "$os_version" = "6" ];then
cat > /etc/yum.repos.d/centos6.repo <<-EOF
[centos]
name=centos6
baseurl=ftp://10.18.40.100/centos6u2
gpgcheck=0
EOF
yum makecache
yum repolist
echo "