shell脚本case_模式匹配详解

简介: 在某种意义上,case语句是if语句的简洁版,case语句适合做字符串模式匹配,如果不同的字符值对应不同的功能则用case语句实现,case无法做比较以及测试命令,最后一个模式可以省略;;command -v 命令用来测试是否是一个命令看$?返回值即可1.1根据系统版本匹配yum源文件

case 模式匹配

一、case语法结构

case 变量名 in
模式1)
​ 命令序列1
​ ;;
模式2)
​ 命令序列2
​ ;;
模式3)
​ 命令序列3
​ ;;
*)
​ 无匹配后命令序列
esac

在某种意义上,case语句是if语句的简洁版,case语句适合做字符串模式匹配,如果不同的字符值对应不同的功能则用case语句实现,case无法做比较以及测试命令,最后一个模式可以省略;;

command -v 命令用来测试是否是一个命令看$?返回值即可

1.1根据系统版本匹配yum源文件

#!/bin/bash
yum_server=192.168.81.250
os_version=$(cat /etc/redhat-release |awk '{print $(NF-1)}'| awk -F '.' '{print $1"."$2}')
[ -d /etc/yum.repos.d/bak ] || mkdir -p /etc/yum.repos.d/bak
mv /etc/yum.repos.d/* /etc/yum.repos.d/bak &>/dev/null
case "$os_version" in
"7.6")
        cat > /etc/yum.repos.d/centos7u6.repo <<-EOF
        [centos7u6]
        name=centos7u6
        baseurl=file:///media
        enabled=1
        gpgcheck=0      
        EOF
        echo "$os_version yum config finish...."
        ;;
"6.5")
        wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo
        echo "$os_version yum config finish...."
        ;;
"5.4")
        wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-5.repo
        echo "$os_version yum config finish...."
        ;;
*)
        echo "error os_version"
esac
echo "finish.."

1.2删除用户,根据输入的字符确认是否删除

#!/bin/bash
-------------------if实现-----------------
read -p "please input a delete username: " user
id $user &>/dev/null
if [ $? -ne 0 ];then
        echo "no such user: $user"
        exit 1        //设置退出状态码
fi
read -p "are you sure delete: $user [y/n]" action
if [ "$action" = y -o "$action" = "yes" -o "$action" = "Y" -o "$action" = "YES" ];then
        userdel -r $user &>/dev/null
        echo "$uer is del..."
else
        echo "you is quit"
fi
-------------------------case实现-----------------
read -p "please input a delete username: " user
id $user &>/dev/null
if [ $? -ne 0 ];then
        echo "no such user: $user"
        exit 1
fi
read -p "are you sure delete: $user [y/n]" action
case $action in
y|Y|yes|YES)
        userdel -r $user &>/dev/null
        echo "$user is del..."
        ;;
*)
        echo "you is quit"
esac

1.3测试某个文件是否是一个命令

#!/bin/bash
command1=/bin/date
if  command -v $command1 &>/dev/null;then
        :   
else
        echo " $command is not keywords"
fi

1.4利用case+if实现批量创建用户

#!/bin/bash
read -p "please input prefix: " prefix
if [ -z $prefix ];then
        echo "error prefix"
        exit 1
fi
read -p "please input create num: " num
if [[ ! $num =~ ^[0-9]+$ ]];then
        echo "error num"
        exit 2
fi
read -p "are you sure create {prefix+num} user[y/n]: " action
case $action in
y|Y|yes|YES)
        echo "begin create....."
        for i in `seq $num`
        do
                user=$prefix$i
                useradd $user &>/dev/null
                if [ $? -eq 0 ];then
                        echo "123" | passwd --stdin $user &>/dev/null
                fi
                echo "$user is add....."
        done
        ;;
n|N|no|NO)
        echo "scripts is quit...."
esac

1.4利用case+if实现批量删除用户

#!/bin/bash
read -p "please input prefix: " prefix
if [ -z $prefix ];then
        echo "error prefix"
        exit 1
fi
read -p "please input delete num: " num
if [[ ! $num =~ ^[0-9]+$ ]];then
        echo "error num"
        exit 2
fi
read -p "are you sure delete {prefix+num} user[y/n]: " action
case $action in
y|Y|yes|YES)
        echo "begin delete....."
        for i in `seq $num`
        do
                user=$prefix$i
                userdel -r $user &>/dev/null
                echo "$user is del....."
        done
        ;;
n|N|no|NO)
        echo "scripts is quit...."
esac

1.5case实现编译安装软件

#!/bin/bash
###############################################################################################
#                           #
# case编译安装工具箱  jxl--20200225                  #
#                                                                                             #
###############################################################################################
tools_dir=/software 
apache_tools_dir=/software/httpd-2.2.17.tar.gz
mysql_tools_dir=/software/mysql-5.5.22.tar.gz
cmake_tools_dir=/software/cmake-2.8.6.tar.gz
nginx_tools_dir=/software/nginx-1.6.0.tar.gz
echo -e "\033[33m begin checking software...\033[0m"
yum list installed | grep 'gcc-c++' &>/dev/null
if [ $? -ne 0 ];then
  read -p "system not gcc,do you install gcc-c++? [y|n]: " action
  case $action in 
  y|Y) 
    yum -y install gcc-c++
    if [ $? -eq 0 ];then
      echo -e "\033[32m gcc-c++ is installed... \033[0m"
    fi
    ;;
  n|N)
    echo -e "\033[31m no gcc-c++ not install tools... \033[0m"
    echo -e "\033[31m scripts is quit... \033[0m"
    exit 1
    ;;
  esac  
fi
echo -e "\033[31m Can install the tool:[httpd|mysql|nginx] \033[0m"
read -p "please input install tool: " tool
case $tool in 
httpd)
  read -p "are you sure install apache_httpd [y|n]: " action_httpd
  if  [ "$action_httpd" = "y" -o "$action_httpd" = "yes" ];then
    yum -y remove httpd
    tar xvf $apache_tools_dir  -C $tools_dir
    cd $tools_dir/httpd-2.2.17
    ./configure --prefix=/usr/local/httpd --enable-so --enable-rewrite --enable-charset-lite --enable-cgi && make && make install
    ln -s /usr/local/httpd/bin* /usr/local/bin &>/dev/null
    cp /usr/local/httpd/bin/apachectl /etc/init.d/httpd
    sed -i -e '1a # chkconfig:35 85 21' /etc/init.d/httpd
    sed -i -e '2a # description:Startup script for the Apache HTTP Server' /etc/init.d/httpd
    systemctl start httpd 
    systemctl enable httpd
    netstat -lnpt | grep httpd
    if [ $? -eq 0 ];then
      echo -e "\033[32m httpd installed....\033[0m"
    fi
  elif [ "$action_httpd" = "n" -o "$action_httpd" = "no" ];then
    echo -e "\033[31m scripts is quit... \033[0m"
    exit 1
  else
    echo -e "\033[31m error action \033[0m" 
    exit 2
  fi
  curl -I 127.0.0.1 &>/dev/null
  if [ $? -eq 0 ];then
    echo -e "\033[32m web page is ok...\033[0m"
  fi
  ;;
mysql)
  read -p "are you sure install mysql [y|n]: " action_mysql
  if  [ "$action_mysql" = "y" -o "$action_mysql" = "yes" ];then
    yum -y remove mariadb
    yum -y install ncurses-devel
    tar xvf $cmake_tools_dir -C $tools_dir
    cd $tools_dir/cmake-2.8.6
    ./configure && make && make install
    tar -xvf $mysql_tools_dir -C $tools_dir
    cd $tools_dir/mysql-5.5.22
    cmake -DCMAKE_INSTALL_PREFIX=/usr/local/mysql -DDEFAULT_CHARSET=utf8 -DDEFAULT_COLLATION=utf8_general_ci -DWICH_EXTRA_CHARSETS=all -DSYSCONFDIR=/etc && make &&make install
    \cp -rf support-files/my-medium.cnf /etc/my.cnf
    \cp -rf support-files/mysql.server /etc/init.d/mysqld
    chmod +x /etc/init.d/mysqld
    ln -s /usr/local/mysql/bin/* /usr/local/bin &>/dev/null
    groupadd mysql &>/dev/null
    useradd -M -s /sbin/nologin -g mysql mysql &>/dev/null
    chown -R mysql:mysql /usr/local/mysql
    /usr/local/mysql/scripts/mysql_install_db --basedir=/usr/local/mysql/ --datadir=/usr/local/mysql/data/ --user=mysql
    /etc/init.d/mysqld start
    netstat -lnpt | grep mysql
    if [ $? -eq 0 ];then
      echo -e "\033[32m mysqld installed...\033[0m"
    fi
  elif [ "$action_mysql" = "n" -o "$action_mysql" = "no" ];then
    echo -e "\033[31m scripts is quit... \033[0m"
    exit 1
  else
    echo -e "\033[31m error action... \033[0m"  
    exit 2
  fi
  ;;
nginx)
  read -p "are you sure install mysql [y|n]: " action_nginx
  if  [ "$action_nginx" = "y" -o "$action_nginx" = "yes" ];then
    yum -y install  openssl-devel zlib-devel pcre-devel 
    tar -xvf $nginx_tools_dir -C $tools_dir
    cd $tools_dir/nginx-1.6.0
    ./configure --prefix=/usr/local/nginx --with-http_ssl_module  && make && make install
    netstat -lnpt | grep 80
    if [ $? -eq 0 ];then
      echo -e "\033[32m port 80 is used...\033[0m"
      echo -e "\033[33m begin update port is 8888!\033[0m"
      sed -i 's/80;/8888;/' /usr/local/nginx/conf/nginx.conf
      if [ $? -eq 0 ];then
        echo -e "\033[33m  port is 8888...\033[0m"
      fi
    fi
    ln -s /usr/local/nginx/sbin/* /usr/local/sbin &>/dev/null
    nginx 
    netstat -lnpt | grep nginx 
    if [ $? -eq 0 ];then
      echo  -e "\033[32m nginx installed...\033[0m"
    fi
   elif [ "$action_nginx" = "n" -o "$action_nginx" = "no" ];then
    echo -e "\033[31m scripts is quit... \033[0m"
    exit 1
     else
        echo -e "\033[31m error action... \033[0m"      
        exit 2
  fi
  ;;
*)
  echo -e "\033[31m The tool is still in development...\033[0m"
esac

1.6case实现简单的跳板机

跳板机适用场景:


1.业务服务器不允许直接连接,通过跳板机进行连接


2.业务服务器不允许root用户登录


跳板机原理


由客户端登录到跳板机服务器,跳板机服务器根据用户输入的ip远程连接对应的应用服务器,客户端不能直接与应用服务器直连,所有主机准备远程连接时使用的账号密码,并设置为密码验证或者密钥验证


此案例需求:


1.做出一个服务器列表


2.根据用户的输入判断去连接哪一台服务器


3.用户连到跳板机服务器就已经将脚本运行好


4.连接进去后不允许退出

#!/bin/bash
clear
trap "" INT HUP OUIT TSTP
while :
do
        cat <<-EOF
                +---------------------------------------------------------+
                |                       jumpserver                        |
                |                       1.192.168.81.210                  |
                |                       2.192.168.81.211                  |
                |                       3.192.168.81.212                  |
                |                       4.192.168.81.213                  |
                +---------------------------------------------------------+
        EOF
        echo -en "\e[33m please input connection host: \e[0m"
        read host
        case  $host in
        1)
                ssh jxl@192.168.81.210
                ;;
        2)
                ssh jxl@192.168.81.211
                ;;
        3)
                ssh jxl@192.168.81.212
                ;;
        4)
                ssh jxl@192.168.81.213
                ;;
        "")
                ;;
        *)
                echo "The host does not exist"
         esac
done

1.7case实现系统管理工具箱

#!/bin/bash
menu(){
cat <<-EOF
+------------------------------------------------------------+
|               系统工具箱                                   |
|               h.help                                       |
|               b.磁盘分区情况                               |
|               d.磁盘使用情况                               |
|               m.内存使用情况                               |
|               u.系统负载情况                               |
|               t.CPU使用情况                                |
|               q.exit                                       |
+------------------------------------------------------------+
EOF
}
clear
while :
do
        menu
        echo  -en "\e[33m Please choose to use tool: \e[0m"
        read  tools
        case $tools in
        h)
                echo "这是一个系统管理工具箱,可以根据所需选择对应的工具"
                menu
                ;;
        b)
                lsblk
                ;;
        d)
                df -hT
                ;;
        m)
                free -g
                ;;
        u)
                uptime
                ;;
        t)       
            top
            ;;
        q)
                exit
                ;;
        "")
                ;;
        *)
                echo -e "\e[31m error option \e[0m"
        esac
done
目录
相关文章
|
Shell
Shell脚本循环控制:shift、continue、break、exit指令
使用这些命令可以让你的Shell脚本像有生命一样动起来。正确使用它们,你的脚本就能像一场精心编排的舞蹈剧目,既有旋律的起伏,也有节奏的跳跃,最终以一场惊艳的表演结束。每一个动作、每一个转折点,都准确、优雅地完成所需要表达的逻辑。如此,你的脚本不只是冰冷的代码,它透过终端的界面,跳着有节奏的舞蹈,走进观众——使用者的心中。
547 60
|
存储 安全 Unix
七、Linux Shell 与脚本基础
别再一遍遍地敲重复的命令了,把它们写进Shell脚本,就能一键搞定。脚本本质上就是个存着一堆命令的文本文件,但要让它“活”起来,有几个关键点:文件开头最好用#!/usr/bin/env bash来指定解释器,并用chmod +x给它执行权限。执行时也有讲究:./script.sh是在一个新“房间”(子Shell)里跑,不影响你;而source script.sh是在当前“房间”里跑,适合用来加载环境变量和配置文件。
1226 9
|
存储 Shell Linux
八、Linux Shell 脚本:变量与字符串
Shell脚本里的变量就像一个个贴着标签的“箱子”。装东西(赋值)时,=两边千万不能有空格。用单引号''装进去的东西会原封不动,用双引号""则会让里面的$变量先“变身”再装箱。默认箱子只能在当前“房间”(Shell进程)用,想让隔壁房间(子进程)也能看到,就得给箱子盖个export的“出口”戳。此外,Shell还自带了$?(上条命令的成绩单)和$1(别人递进来的第一个包裹)等许多特殊箱子,非常有用。
1293 2
|
Web App开发 缓存 安全
Linux一键清理系统垃圾:释放30GB空间的Shell脚本实战​
这篇博客介绍了一个实用的Linux系统盘清理脚本,主要功能包括: 安全权限检查和旧内核清理,保留当前使用内核 7天以上日志文件清理和系统日志压缩 浏览器缓存(Chrome/Firefox)、APT缓存、临时文件清理 智能清理Snap旧版本和Docker无用数据 提供磁盘空间使用前后对比和大文件查找功能 脚本采用交互式设计确保安全性,适合定期维护开发环境、服务器和个人电脑。文章详细解析了脚本的关键功能代码,并给出了使用建议。完整脚本已开源,用户可根据需求自定义调整清理策略。
1655 1
|
数据采集 监控 Shell
无需Python:Shell脚本如何成为你的自动化爬虫引擎?
Shell脚本利用curl/wget发起请求,结合文本处理工具构建轻量级爬虫,支持并行加速、定时任务、增量抓取及分布式部署。通过随机UA、异常重试等优化提升稳定性,适用于日志监控、价格追踪等场景。相比Python,具备启动快、资源占用低的优势,适合嵌入式或老旧服务器环境,复杂任务可结合Python实现混合编程。
|
存储 Unix Shell
确定Shell脚本在操作系统中的具体位置方法。
这对于掌握Linux的文件系统组织结构和路径方面的理解很有帮助,是我们日常工作和学习中都可能使用到的知识。以上讲解详细清晰,应用简便,是每一个想要精通操作系统的计算机爱好者必备的实用技能。
2164 17
|
Linux Shell 数据安全/隐私保护
Centos或Linux编写一键式Shell脚本创建用户、组、目录分配权限指导手册
Centos或Linux编写一键式Shell脚本创建用户、组、目录分配权限指导手册
879 3
|
关系型数据库 MySQL Shell
MySQL 备份 Shell 脚本:支持远程同步与阿里云 OSS 备份
一款自动化 MySQL 备份 Shell 脚本,支持本地存储、远程服务器同步(SSH+rsync)、阿里云 OSS 备份,并自动清理过期备份。适用于数据库管理员和开发者,帮助确保数据安全。
|
Shell
一个用于添加/删除定时任务的shell脚本
一个用于添加/删除定时任务的shell脚本
657 1