• 流程控制语句if基本概述


    1. 流程控制语句if基本概述

    01. 单分支结构

    if [ 如果你有房 ];then    我就嫁给你fi
    
    #示例
    
    [root@qiudao ~/shell]# cat if-1.sh#!/usr/bin/bashif which ls;thenecho "ok"fi
    
    #执行脚本
    
    [root@qiudao ~/shell]# sh if-1.sh/usr/bin/lsok
    

    02. 双分支结构

    if [ 如果你有房 ];then    我就嫁给你else    再见fi
    
    #示例
    
    [root@qiudao ~/shell]# cat if-2.sh#!/usr/bin/bashif [ $# -ne 1 ];then    echo "请输入一个参数"    exitfiif grep "$1" /etc/passwd;thenecho "ok!"elseecho "error!"fi
    
    #执行脚本
    
    [root@qiudao ~/shell]# sh if-2.sh rootroot:x:0:0:root:/root:/bin/bashoperator:x:11:0:operator:/root:/sbin/nologinok!
    

    03. 多分支结构

    if [ 如果你有钱 ];then 我就嫁给你elif [ 你有房 ];then 我就嫁给你elif [ 你很努力能吃苦 ];then 我们试试else 再见fi

    #示例
    判断用户是否存在
    
    #脚本
    read -p "please input your user: " user
    #判断
    if id $user &>/dev/null;then
        if ls /home/$user &>/dev/null;then
            echo "还用户 $user 存在该系统"
            echo "该用户存在家目录"
        else
            echo "还用户 $user 存在该系统"
            echo "该用户不存在家目录"
        fi
    else
        if ls /home/$user &>/dev/null;then
            echo "还用户 $user 不存在该系统"
            echo "该用户存在家目录"
        else
            echo "还用户 $user 不存在该系统"
            echo "该用户不存在家目录"
        fi
    fi
    

    2. 流程控制语句if文件比较

    01. if语句中的文件比较

    选项 说明 示例
    -e 如果文件或目录存在则为真 [ -e file ]
    -s 如果文件存在且至少有一个字符则为真 [ -s file ]
    -d 如果文件存在且为目录则为真 [ -d file ]
    -f 如果文件存在且为普通文件则为真 [ -f file ]
    -r 如果文件存在且可读则为真 [ -r file ]
    -w 如果文件存在且可写则为真 [ -w file ]
    -x 如果文件存在且可执行则为真 [ -x file ]

    02. 语法示例

    #语法示例一:
    
    [root@qiudao ~/shell]# cat if-4.sh
    if [ -e /etc/hosts ];then
        echo "ok"
    else
        echo "err"
    fi
    
    #执行脚本
    [root@qiudao ~/shell]# sh if-4.sh
    ok
    
    #语法示例二:
    [root@qiudao ~/shell]# cat if-4.sh
    if [ -e /etc/hostss ];then
        echo "ok"
    else
        echo "err"
    fi
    
    #执行脚本
    [root@qiudao ~/shell]# sh if-4.sh
    err
    
    #常用测试
    [root@qiudao ~/shell]# [ -f /etc/hosts ] && echo $?
    0
    [root@qiudao ~/shell]# [ -f /etc/hostss ] && echo $?
    [root@qiudao ~/shell]# [ ! -f /etc/hosts ] || echo $
    

    判断文件是否存在,返回方式

    [root@qiudao ~/shell]# [ -f /etc/hosts ] && echo "文件存在" || echo "文件不存在"
    文件存在
    
    [root@qiudao ~/shell]# [ -f /etc/hosts1 ] && echo "文件存在" || echo "文件不存在"
    文件不存在
    
    [root@qiudao ~/shell]# [ -d /tmp ] && echo "目录存在" || echo "目录不存在"
    目录存在
    
    [root@qiudao ~/shell]# [ -d /tmp1 ] && echo "目录存在" || echo "目录不存在"
    目录不存在
    

    使用变量的方法进行判断

    [root@qiudao ~/shell]# dir=/etc1/;[ -d $dir ] && tar zcf etc.tar.gz $dir || echo "$dir目录不存在"
    /etc1/目录不存在
    
    **03. 文件比较场景实践,备份数据库**
    
    #1.备份mysql,手动输入你需要备份的库名称
    
    1)提示用户手动输入库名称:read
    2)如果用户输入数据库名称,则执行mysqldump命令备份
    
    3)备份到哪,/backup/mysq
    
    #示例脚本一:
    [root@qiudao ~/shell]# cat mysql_backup1.sh
    #!/usr/bin/bash
    DestPath=/backup/mysql
    M_User=root
    M_Pass=123.com
    [ -d $DestPath ] || mkdir -p $DestPath
    
    read -p "请输入你要备份的数据库名称: " db
    /usr/bin/mysqldump -u$M_User -p$M_Pass --single-transaction -R -B $db > $DestPath/${db}_$(date +%F).sql
    if [ $? -eq 0 ];then
        echo "------------------"
        echo "$db 数据库备份成功"
        echo "------------------"
    fi
    
    #执行脚本
    [root@qiudao ~/shell]# sh mysql_backup1.sh
    

    请输入你要备份的数据库名称: wordpress

    wordpress 数据库备份成功

    #示例脚本二:
    [root@qiudao ~/shell]# cat mysql_backup2.sh
    #!/usr/bin/bash
    DestPath=/backup/mysql
    #M_User=root
    #M_Pass=123.com
    [ -d $DestPath ] || mkdir -p $DestPath
    
    read -p "请输入你要备份的数据库名称: " db
    read -p "请输入你要备份的数据库用户: " M_User
    read -p "请输入你要备份的数据库密码: " M_Pass
    /usr/bin/mysqldump -u$M_User -p$M_Pass --single-transaction -R -B $db > $DestPath/${db}_$(date +%F).sql
    if [ $? -eq 0 ];then
        echo "------------------"
        echo "$db 数据库备份成功"
        echo "------------------"
    fi
    
    #执行脚本
    [root@qiudao ~/shell]# sh mysql_backup2.sh
    请输入你要备份的数据库名称: wordpress
    请输入你要备份的数据库用户: root
    

    请输入你要备份的数据库密码: 123.com

    wordpress 数据库备份成功

    3. 流程控制语句if整数比较

    01. 数值比较[整数1 操作符 整数2 ]

    选项 说明 示例
    -eq 等于则条件为真 [ 1 -eq 10 ]
    -ne 不等于则条件为真 [ 1 -ne 10 ]
    -gt 大于则条件为真 [ 1 -gt 10 ]
    -lt 小于则条件为真 [ 1 -lt 10 ]
    -ge 大于等于则条件为真 [ 1 -ge 10 ]
    -le 小于等于则条件为真 [ 1 -le 10 ]
    01. 语法示例**
    
    #等于
    [root@qiudao ~/shell]# [ 1 -eq 2 ] && echo "成立" || echo "不成立"
    不成立
    
    [root@qiudao ~/shell]# [ 1 -eq 1 ] && echo "成立" || echo "不成立"
    成立
    
    
    
    #大于等于
    [root@qiudao ~/shell]# [ 10 -ge 1 ] && echo "成立" || echo "不成立"
    成立
    
    [root@qiudao ~/shell]# [ 10 -ge 11 ] && echo "成立" || echo "不成立"
    不成立
    
    
    
    #小于
    [root@qiudao ~/shell]# [ 10 -lt 11 ] && echo "成立" || echo "不成立"
    成立
    
    [root@qiudao ~/shell]# [ 10 -lt 9 ] && echo "成立" || echo "不成立"
    不成立
    
    
    
    #大于
    [root@qiudao ~/shell]# [ 10 -gt 9 ] && echo "成立" || echo "不成立"
    成立
    [root@qiudao ~/shell]# [ 10 -gt 11 ] && echo "成立" || echo "不成立"
    不成立
    
    
    
    #小于
    [root@qiudao ~/shell]# [ 10 -le 11 ] && echo "成立" || echo "不成立"
    成立
    
    [root@qiudao ~/shell]# [ 10 -le 9 ] && echo "成立" || echo "不成立"
    不成立
    
    
    
    #不等于
    [root@qiudao ~/shell]# [ 10 -ne 11 ] && echo "成立" || echo "不成立"
    成立
    
    [root@qiudao ~/shell]# [ 10 -ne 10 ] && echo "成立" || echo "不成立"
    不成立
    

    02. 场景实践一:编写一个脚本,检测服务是否运行

    1)如何判断我们服务是否是运行 systemctl status sshd
    2)判断前者命令执行是否成功,成功则输出运行,失败则输出程序没有运行

    #示例脚本如下:
    [root@qiudao ~/shell]# cat systemctl.sh
    #!/usr/bin/bash
    if [ $# -ne 1 ];then
        echo "请输入一个服务名称,示例 sh $0 [sshd|httpd|nginx|....]"
        exit
    fi
    
    systemctl status "$1" &>/dev/null
    rc=$?
    if [ $rc -eq 0 ];then
        echo "$1 服务正在运行"
    elif [ $rc -eq 4 ];then
        echo "$1 没有这个服务"
    else
        echo "$1 服务没有运行"
    fi
    
    #执行脚本
    [root@qiudao ~/shell]# sh systemctl.sh
    请输入一个服务名称,示例 sh systemctl.sh [sshd|httpd|nginx|....]
    [root@qiudao ~/shell]# sh systemctl.sh sshd
    sshd 服务正在运行
    
    [root@qiudao ~/shell]# sh systemctl.sh ssh
    ssh 没有这个服务
    
    [root@qiudao ~/shell]# sh systemctl.sh firewalld
    firewalld 服务没有运行
    

    03. 场景实践二:查看磁盘/分区当前使用状态,如果使用率超过80%则报警发邮件

    1)怎么查看磁盘使用率  
    2)怎么提取使用率

    3)判断,整数

    #示例脚本如下:
    [root@qiudao ~/shell]# cat disk_use.sh
    #!/usr/bin/bash
    disk_use=$(df -h|grep "/$"|awk '{print $(NF-1)}')
    if [ ${disk_use/\%/} -ge 80 ];then
        echo "你的磁盘使用率过高... ${disk_use}" /bin/false
    else
        echo "你的磁盘使用率正常... ${disk_use}" /bin/true
    fi
    
    #执行脚本
    [root@qiudao ~/shell]# sh disk_use.sh
    你的磁盘使用率正常... 6%
    

    04. 场景实践三:条件测试,创建用户

    #示例脚本
    [root@qiudao ~/shell]# cat user.sh
    #!/usr/bin/bash
    read -p "Please input a username: " user
    
    id $user &>/dev/null;
    if [ $? -eq 0 ]; then
        echo "user $user already exists"
    else
        useradd $user
        if [ $? -eq 0 ];then
            echo "$user is created."
        fi
    fi
    
    #执行脚本
    [root@qiudao ~/shell]# sh user.sh
    Please input a username: user01
    user01 is created.
    [root@qiudao ~/shell]# sh user.sh
    Please input a username: user01
    user user01 already exists
    

    05. 场景实践四:函数库使用,判断url地址是否能通

    [root@qiudao ~/shell]## cat ping.sh
    
    [ -f /etc/init.d/functions ] && . /etc/init.d/functions
    read -p "请输入一个网址: " url
    ping -c 1 -W 1 $url &>/dev/null
    rc=$?
    if [ $rc -eq 0 ];then
            action "ping $url is" /bin/true
        else
            action "ping $url is" /bin/false
    fi
    
    

    4. 流程控制语句if字符比较

    01. if字符比较

    选项 说明 示例
    == 等于则条件为真 [ "$a" == "$b" ]
    != 不相等则条件为真 [ "$a" != "$b" ]
    -z 字符串的长度为零则为真 [ -z "$a" ]
    -n 字符串的长度不为零则为真 [ -n "$a" ]

    02. 字符串比对,必须加双引号

    #语法示例:
    [root@qiudao ~/shell]# [ "$USER" == "root" ] && echo $?
    0
    [root@qiudao ~/shell]# [ "$USER" == "roo" ] && echo $?
    [root@qiudao ~/shell]# [ "$USER" == "roo" ] || echo $?
    1
    [root@qiudao ~/shell]# [ "$USER" != "root" ] && echo $?
    [root@qiudao ~/shell]# [ "$USER" != "roo" ] && echo $?
    0
    
    #字符串长度为0
    [root@qiudao ~]# AAA=""
    [root@qiudao ~]# echo $AAA
    
    [root@qiudao ~]# echo ${#AAA}
    0
    [root@qiudao ~]# [ -z "$AAA" ] && echo $?
    0
    
    #字符串长度不为0
    [root@qiudao ~]# BBB=1
    [root@qiudao ~]# [ -n "$BBB" ] && echo $?
    0
    
    #脚本示例:
    [root@qiudao ~/shell]# cat if-9.sh
    #!/bin/bash
    read -p "请输入[yes|no]:" tt
    if [ "$tt" == "yes" ];then
        echo "ok"
    fi
    
    #执行脚本
    [root@qiudao ~/shell]# sh if-9.sh
    请输入[yes|no]:yes
    ok
    [root@qiudao ~/shell]# sh if-9.sh
    请输入[yes|no]:no
    

    03. 多整数比对条件

    #-a 并且,-o 或者
    
    [root@qiudao ~]# [ 1 -lt 2 -a 5 -gt 10 ] ;echo $?1[root@qiudao ~]# [ 1 -lt 2 -o 5 -gt 10 ] ;echo $?0
    
    #正则比对会用到[[]],|| 或者,&& 并且
    
    [root@qiudao ~]# [[ 1 -lt 2 || 5 -gt 10 ]] ;echo $?
    0
    [root@qiudao ~]# [[ 3 -lt 2 || 5 -gt 10 ]] ;echo $?
    1
    [root@qiudao ~]# [[ 3 -lt 2 || 5 -gt 2 ]] ;echo $?
    0
    [root@qiudao ~]# [[ 1 -lt 2 && 5 -gt 10 ]] ;echo $?
    1
    [root@qiudao ~]# [[ 3 -lt 2 && 5 -gt 10 ]] ;echo
    

    04. 场景实践:根据学生录入的成绩判断,学生的优劣

    1-59 补考,60-80 合格,80-100 优秀
    1)read读入学生输入的分数
    
    2)比较分数,看否和哪一个条件
    
    #示例脚本一:单条件
    [root@qiudao ~/shell]# cat if-6.sh
    read -p "请输入你的分数: " fs
    if [ $fs -lt 60 ];then
        echo "补考"
    elif [ $fs -gt 100 ];then
        echo "顽皮"
    elif [ $fs -ge 80 ];then
        echo "优秀"
    elif [ $fs -ge 60 ];then
        echo "合格"
    fi
    
    #执行脚本
    [root@qiudao ~/shell]# sh if-6.sh
    请输入你的分数: 59
    补考
    
    [root@qiudao ~/shell]# sh if-6.sh
    请输入你的分数: 60
    合格
    
    [root@qiudao ~/shell]# sh if-6.sh
    请输入你的分数: 80
    优秀
    
    [root@qiudao ~/shell]# sh if-6.sh
    请输入你的分数: 101
    顽皮
    
    #示例脚本二:多条件
    [root@qiudao ~/shell]# cat if-7.sh
    read -p "请输入你的分数: " fs
    if [ $fs -gt 0 -a $fs -lt 60 ];then
        echo "补考"
    elif [ $fs -ge 60 -a $fs -lt 80 ];then
        echo "合格"
    elif [ $fs -ge 80 -a $fs -le 100 ];then
        echo "优秀"
    else
        echo "顽皮"
    fi
    
    #执行脚本
    [root@qiudao ~/shell]# sh if-7.sh
    请输入你的分数: 4
    补考
    
    [root@qiudao ~/shell]# sh if-7.sh
    请输入你的分数: 60
    合格
    
    [root@qiudao ~/shell]# sh if-7.sh
    请输入你的分数: 89
    优秀
    
    [root@qiudao ~/shell]# sh if-7.sh
    请输入你的分数: 101
    顽皮
    
    [root@qiudao ~/shell]# sh if-7.sh
    请输入你的分数: -9
    顽皮
    
    [root@qiudao ~/shell]# sh if-7.sh
    请输入你的分数: lkhdjf
    if-7.sh: line 2: [: lkhdjf: integer expression expected
    if-7.sh: line 4: [: lkhdjf: integer expression expected
    if-7.sh: line 6: [: lkhdjf: integer expression expected
    顽皮
    
    
    
    #示例脚本三:条件判断
    
    
    
    [root@qiudao ~/shell]# cat if-8.sh
    read -p "请输入你的分数: " fs
    
    #判断数字
    
    expr $fs + 1 &>/dev/null
    if [ $? -ne 0 ];then
        echo "请输入数字。" && exit
    fi
    
    #判断是否为空值
    
    if [ -z $fs ];then
        echo "不要尝试直接回车,不支持" && exit
    fi
    #判断成绩
    
    if [ $fs -gt 0 -a $fs -lt 60 ];then
        echo "补考"
    elif [ $fs -ge 60 -a $fs -lt 80 ];then
        echo "合格"
    elif [ $fs -ge 80 -a $fs -le 100 ];then
        echo "优秀"
    else
        echo "顽皮"
    fi
    
    #执行脚本
    [root@qiudao ~/shell]# sh if-8.sh
    请输入你的分数: tt
    请输入数字。
    
    [root@qiudao ~/shell]# sh if-8.sh
    请输入你的分数:
    不要尝试直接回车,不支持
    
    [root@qiudao ~/shell]# sh if-8.sh
    请输入你的分数: 88
    优秀
    

    5. 流程控制语句if正则比较

    01. 正则比对示例**
    
    #单括号无法使用正则语法
    [root@qiudao ~]# [ "$USER" =~ ^r ];echo $?
    -bash: [: =~: binary operator expected
    2
    
    #使用双[]才可以
    [root@qiudao ~]# [[ "$USER" =~ ^r ]];echo $?
    0
    
    #判断变量是否为数字
    [root@qiudao ~]# num=123
    [root@qiudao ~]# [[ "$num" =~ ^[0-9]+$ ]];echo $?
    0
    [root@qiudao ~]# num=1
    

    02. 示例一:判断用户输入的是否为整数

    #示例脚本:
    
    [root@qiudao ~/shell]# cat if-10.sh
    #!/bin/bashread -p "请输入一个整数:" num
    if [[ ! "$num" =~ ^[0-9]+$ ]];then    
    	echo "你输入的不是整数,程序退出!!!"    
    	exit
    fi
    	echo "你输入的整数是 $num "
    
    #执行脚本:
    
    [root@qiudao ~/shell]# sh if-10.sh
    请输入一个整数:aa
    你输入的不是整数,程序退出!!!
    [root@qiudao ~/shell]# sh if-10.sh
    请输入一个整数:89
    你输入的整数是 89
    [root@qiudao ~/shell]# sh if-10.sh
    请输入一个整数:-4
    你输入的不是整数,程序退出!!!
    [root@qiudao ~/shell]# sh if-10.sh
    请输入一个整数:0.6
    你输入的不是整数,程序退出!!!
    

    03. 示例二:写一个创建用户的脚本,需要输入创建用户的前缀,比如oldboy,以及后缀。比如123。

    #示例脚本:
    [root@qiudao ~/shell]# cat if-11.sh
    #!/usr/bin/bash
    read -p "请输入用户的前缀: " qz
    if [[ ! $qz =~ ^[a-Z]+$ ]];then
        echo "你输入的不是english...."
        exit
    fi
    read -p "请输入创建用户的后缀: " hz
    if [[ $hz =~ ^[0-9]+$ ]];then
        user=${qz}${hz}
        id $user &>/dev/null
        if [ $? -eq 0 ];then
            echo "用户已经存在 $user"
        else
            useradd $user
            echo "用户创建成功 $user"
        fi
    else
    echo "你输入的不是数字...."
    exit
    fi
    
    #执行脚本
    [root@qiudao ~/shell]# sh if-11.sh
    请输入用户的前缀: oldboy
    请输入创建用户的后缀: 123
    用户创建成功 oldboy123
    [root@qiudao ~/shell]# sh if-11.sh
    请输入用户的前缀: oldboy
    请输入创建用户的后缀: 123
    用户已经存在 oldboy123
    
    
    

    6. 流程控制语句if场景示例

    01. 场景示例:使用root用户清空/var/log/messages日志,并每次执行保留最近100行

    1)判断必须是root 2)判断文件必须存在 3)清空后需要保留最近100行

    #示例脚本
    
    [root@qiudao ~/shell]# cat if-12.sh
    #!/usr/bin/bash
    #1.判断用户是否是root,并且UID为0
    if [ $UID -eq 0 ] && [ $USER == "root" ] ;then
        #2.判断文件是否存在
        if [ -f /var/log/messages ];then
            #保留最近100行
            tail -100 /var/log/messages >/var/log/messages.bak
            cat /var/log/messages.bak >/var/log/messages        		echo "=======成功=========="
        else
            echo "文件/var/log/messages 不存在"
        fi    
    else
        echo "$USER 对$0 脚本没有执行权限"
    fi
    
    #执行脚本
    [root@qiudao ~/shell]# sh if-12.sh=======成功==========
    

    02. 场景示例:判断sshd服务是否正常启动

    1)手动怎么判断服务是正常

    2)先判断服务是否是启动的      
    3)如果服务是启动再判断端口是否存在

    4)最后判断进程是否存在

    #示例脚本如下:
    [root@qiudao ~/shell]# cat if-13.sh
    #!/usr/bin/bash
    #1.判断服务是否启动
    
    ssh_status=$(systemctl status sshd|awk '/^.*Active/ {print $2}')
    if [ "$ssh_status" == "active" ];then
        sleep 1
        echo "sshd服务监测是 ${ssh_status}......"
    else
        sleep 1
        echo "sshd服务监测是 ${ssh_status}......."
    fi
    
    #2.判断端口是否存在
    
    netstat -lntp|grep "sshd" &>/dev/null
    if [ $? -eq 0 ];then
        sleep 1
        echo "sshd服务端口存活....."
    else
        sleep 1
        echo "sshd服务端口不存在...."
    fi
    
    #3.判断进程是否存在
    
    ps axu|grep sshd|grep -v grep|grep -v "pts" &>/dev/null
    if [ $? -eq 0 ];then
        sleep 1
        echo "sshd服务进程是存在..."
    else
        sleep 1
        echo "sshd服务进程不存在...."
        ps axu|grep sshd|grep -v grep
    fi
    
    #执行脚本:
    [root@qiudao ~/shell]# sh if-13.sh
    sshd服务监测是 active......
    sshd服务端口存活.....
    sshd服务进程是存在..
    
    [root@qiudao ~/shell]# sh if-13.sh
    sshd服务监测是 inactive.......
    sshd服务端口不存在....
    sshd服务进程不存在....
    root 26830 0.0 0.6 161496 6152 ? Ss 10:00 0:00 sshd: root@pts/0
    

    03. 场景示例:根据不同的系统安装不同的yum源

    1)系统的版本如何判断

    [root@backup scripts]# cat yum1.sh
    #!/bin/bash
    #定义变量
    Ver=$(cat /etc/redhat-release  |awk  '{print $(NF-1)}')
    #根据变量值的结果进行判断
    if [ ${Ver%%.*} -eq 6 ];then
        #安装centos-6系列的yum源
        #清空旧的yum源
        rm -f /etc/yum.repos.d/*  &>/dev/null
        #安装base源
        echo "你的操作系统为:$Ver ,开始安装${Ver%%.*}的Base源"
        curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo  &>/dev/null
        if [ $? -eq 0 ];then
            echo "$Ver 系统的Base安装成功!"
        else
            echo "$Ver 系统的Base安装失败!"
        fi
        #安装epel源
        curl -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-6.repo &>/dev/null
        if [ $? -eq 0 ];then
            echo "$Ver 系统的Epel安装成功!"
        else
            echo "$Ver 系统的Epel安装失败!"
        fi
    elif [ ${Ver%%.*} -eq 7 ];then
        #安装centos-7系列的yum源
        #清空旧的yum源
        rm -f /etc/yum.repos.d/*  &>/dev/null
        #安装base源
        echo "你的操作系统为:$Ver ,开始安装${Ver%%.*}的Base源"
        curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo  &>/dev/null
        if [ $? -eq 0 ];then
            echo "$Ver 系统的Base安装成功!"
        else
            echo "$Ver 系统的Base安装失败!"
        fi
        #安装Epel源
        echo "你的操作系统为:$Ver ,开始安装${Ver%%.*}的Epel源"
        curl -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo &>/dev/null
        if [ $? -eq 0 ];then
            echo "$Ver 系统的Epel安装成功!"
        else
            echo "$Ver 系统的Epel安装失败!"
        fi
    else
        echo "你的操作系统不符合我们的要求。"
        exit
    fi
    
    
    

    7. 流程控制语句case基本概述

    01. case用来实现对程序流程的选择、循环等进行控制。语法如下:

    [root@backup scripts]# cat rc.sh 
    #!/bin/bash
    #调用库函数
    [ -f /etc/init.d/functions ] && source /etc/init.d/functions
    #判断位置变量
    if [ $# -ne 1 ];then
        echo "请输入一个参数,方法如下:"
        echo "Usage: $0 {start|stop|status}"
        exit
    fi
    #编写case
    state=$1
    Rsync=/var/run/rsync.pid
    case $state in
        start)
            if [ -f $Rsync ];then
                action " Rsync 正在运行。。。。" /bin/true
            else
                touch $Rsync
                /usr/bin/rsync --daemon &>/dev/null
                if [ $? -eq 0 ];then
                    action "Rsync 服务启动成功" /bin/true
                else
                    action "Rsync 服务启动失败" /bin/false
                fi
            fi
            ;;
        stop)
            if [ -f $Rsync ];then
                rm -f $Rsync && pkill rsync &>/dev/null
                if [ $? -eq 0 ];then
                    action "Rsync 服务关闭" /bin/true
                else
                    action "Rsync 没用运行" /bin/true
                fi
            else
                action "Rsync 没有运行" /bin/true
            fi
            ;;
        restart)
            if [ -f $Rsync ];then
                action "Rsync 正在运行。。。" /bin/true
                rm -f $Rsync && pkill rsync  &>/dev/null
                if [ $? -eq 0 ];then
                    action "Rsync 服务关闭成功" /bin/false
                else
                    action "Rsync 服务关闭失败" /bin/false
                fi
            else
                action "Rsync 服务没有运行" /bin/false
            fi
            touch $Rsync
             /usr/bin/rsync --daemon  &>/dev/null
            if [ $? -eq 0 ];then
                action "Rsync 服务重启成功" /bin/true
            else
                action "Rsync 服务启动失败" /bin/false
            fi
            ;;
        *)
            echo "请输入一个参数,方法如下:"
            echo "Usage: $0 {start|stop|status|restart}"
            exit
    esac
    
    ## [root@qiudao /scripts]# sh case1.sh
    
    | 1. Installed PHP 5.5
    | 2. Installed PHP 5.6
    | 3. Installed PHP 7.0
    
    ## | 4. Exit
    
    请输入你要安装的php版本[1|2|3|4]: 1
    正在安装5.5版本的PHP,请稍后....
    安装5.5版本的PHP安装成功!
    
    ## [root@qiudao /scripts]# sh case1.sh
    
    | 1. Installed PHP 5.5
    | 2. Installed PHP 5.6
    | 3. Installed PHP 7.0
    
    ## | 4. Exit
    
    请输入你要安装的php版本[1|2|3|4]: 4
    

    8. 流程控制语句case场景示例

    01. 场景示例一:写一个rsync的启动和停止的脚本

    1.如何启动的命令 rsync --daemon
        ps aux|grep rsync|grep -v grep
    2.如何停止kill,

    pkill rsync

    使用if判断

    [root@qiudao /scripts]# cat daemon.sh
    #!/usr/bin/bash
    source /etc/init.d/functions
    rs=$1
    #1.如果用户传递的第一个位置参数是start则执行如下if语句
    
    if [ $rs == "start" ];then
    
    #在启动rsync服务前,先判断是否存在pid文件(手动创建的pid文件)
    if [ ! -f /var/run/rsync.pid ];then
        #如果不存在pid,则手动创建并启动服务(加锁机制)
            touch /var/run/rsync.pid
            rsync --daemon
            action "Rsync Starting...." /bin/true
    else
            action "Rsync Service Running..." /bin/false
    fi
    
    elif [ $rs == "stop" ];then
    if [ ! -f /var/run/rsync.pid ];then
            action "Rsync Service Stoppend...." /bin/false
    else
            #如果停止服务,一定需要删除pid
            rm -f /var/run/rsync.pid
            pkill rsync
            action "Rsync Stopting....." /bin/true
    fi
    
    elif [ $rs == "status" ];then
    if [ ! -f /var/run/rsync.pid ];then
            echo "Rsync Service Status InActive...."
    else
            Rsync_Status=$(ps aux|grep rsync|grep -v grep|awk '{print $2}')
            echo "Rsync Service Status Active( pid号为:"$Rsync_Status" )"
    fi
    else
        echo "USAGE: $0 {start|stop}"
        exit
    fi
    

    使用case语句

    root@qiudao /scripts]#     cat rsync.sh
    #!/usr/bin/bash
    source /etc/init.d/functions
    rs=$1
    
    case $rs in
        start)
         if [ ! -f /var/run/rsync.pid ];then
                touch /var/run/rsync.pid
                rsync --daemon
                action "Rsync Starting...." /bin/true
         else
                action "Rsync Service Running..." /bin/false
        fi
            ;;
    
        stop)
         if [ ! -f /var/run/rsync.pid ];then
                action "Rsync Service Stoppend...." /bin/false
         else
                rm -f /var/run/rsync.pid
                pkill rsync
                action "Rsync Stopting....." /bin/true
         fi
            ;;
    
        status)
         if [ ! -f /var/run/rsync.pid ];then
                echo "Rsync Service Status InActive...."
        else
                Rsync_Status=$(ps aux|grep rsync|grep -v grep|grep -v pts|awk '{print $2}')
                echo "Rsync Service Status Active( "$Rsync_Status" )"
        fi
            ;;
        *)
            echo "USAGE: $0 {start|stop|status}"
            exit
    esac
    

    02. 场景示例二:编写一个nginx的启动和停止脚本。

    1.如何启动 /usr/sbin/nginx
    2.如何停止     /usr/sbin/nginx -s stop
    3.如何重载    /usr/sbin/nginx -s reload

    [root@backup scripts]# cat status1.sh
    #!/bin/bash
    
    #判断用户是否输入一个位置参数
    if [ $# -ne 1 ];then
        echo "请输入一个参数,具体事例如下:"
        echo "Usage: $0 {start|stop|reloas}"
        exit
    fi
    #判断nginx是否开启
    rc=/run/nginx.pid
    #编写case语句
    dir=$1
    case $dir in
        start)
            /usr/sbin/nginx &>/dev/null
            if [ $? -eq 0 ];then
                echo "nginx服务已启动:"
            else
                echo "nginx服务启动失败"
            fi
            ;;
        stop)
            if [ -f $rc ];then
                echo "nginx在启动zhaungtai"
                /usr/sbin/nginx -s stop &>/dev/null
                if [ $? -eq 0 ];then
                    echo "nginx服务停止成功"
                else
                    echo "nginx服务停止失败"
                fi
            else:
                echo "nginx 已经停止"
    
            fi
            ;;
        reload)
            #判断nginx服务是否在启动状态
            if [ -f $rc ];then
                echo "nginx 已启动"
                /usr/sbin/nginx -s reload &>/dev/null
                if [ $? -eq 0 ];then
                     echo "nginx重载成功"
                else
                    echo "nginx重载失败"
                fi
            else
                /usr/sbin/nginx &>/dev/null
                if [ $? -eq 0 ];then
                    /usr/sbin/nginx -s reload &>/dev/null
                    if [ $? -eq 0 ];then
                        echo "nginx重载成功"
                    else
                        echo "nginx重载失败"
                    fi
                else
                    echo "nginx启动失败,需要重新检测"
                fi
            fi
            ;;
        *)
            echo "请输入一个参数,具体事例如下:"
            echo "Usage: $0 {start|stop|reloas}"
            exit
    esac
    
    
    [root@qiudao /scripts]# cat case-4.sh
    #!/usr/bin/bash
    source /etc/init.d/functions
    
    #加锁
    
    if [ -f /tmp/nginx.lock ];then
        echo "此脚本正在运行,请稍后....."
        exit
    fi
    touch /tmp/nginx.lock
    rc=$1
    case $rc in
        start)
            if [ -f /var/run/nginx.pid ];then
                action "nginx服务已经启动...." /bin/false
                exit
    	    else
                /usr/sbin/nginx
                action "nginx服务启动成功..." /bin/true
            fi
            ;;
        stop)
            if [ -f /var/run/nginx.pid ];then
                /usr/sbin/nginx -s stop
                if [ $? -eq 0 ];then
                    action "nginx关闭成功..." /bin/true
                else
                    action "nginx关闭失败..." /bin/false
                fi
            else
                action "nginx已经关闭...[error] open() /run/nginx.pid" /bin/false
            fi        
            ;;
        reload)
            if [ -f /var/run/nginx.pid ];then
                sleep 2
                /usr/sbin/nginx -s reload
                if [ $? -eq 0 ];then
                    action "nginx重载成功..." /bin/true
                else
                    action "nginx重载失败..." /bin/false    
                fi
            else
                action "nginx没有启动,无法完成重载" /bin/false
            fi
            ;;
        status)
            if [ -f /var/run/nginx.pid ];then
                nginx_pid=$(cat /var/run/nginx.pid)
                echo "nginx ( $nginx_pid ) is running...."
            else
                echo "nginx is Not running...."
            fi
            ;;
        
        *)
            echo "USAGE: $0 [ start | stop | reload | status ] "
    
    esac
    
    #解锁
    
    rm -f /tmp/nginx.lock
    
    #加强版
    
    
    
    [root@qiudao /scripts]# cat case-5.sh
    #!/usr/bin/bash
    source /etc/init.d/functions
    
    #加锁
    
    Lock=/tmp/nginx.lock
    if [ -f $Lock ];then
        echo "此脚本正在运行,请稍后....."
        exit
    fi
    touch $Lock
    
    rc=$1
    case $rc in
        start)
            if [ -f /var/run/nginx.pid ];then
            sleep 10
                action "nginx服务已经启动...." /bin/false
    else
                /usr/sbin/nginx
                action "nginx服务启动成功..." /bin/true
            fi
            ;;
        stop)
            if [ -f /var/run/nginx.pid ];then
                /usr/sbin/nginx -s stop
                if [ $? -eq 0 ];then
                    action "nginx关闭成功..." /bin/true
                else
                    action "nginx关闭失败..." /bin/false
                fi
            else
                action "nginx已经关闭...[error] open() /run/nginx.pid" /bin/false
            fi
            
            ;;
        reload)
            if [ -f /var/run/nginx.pid ];then
                /usr/sbin/nginx -t &>/dev/null
                if [ $? -eq 0 ];then
                    /usr/sbin/nginx -s reload
                    if [ $? -eq 0 ];then
                        action "nginx重载成功..." /bin/true
                    else
                        action "nginx重载失败..." /bin/false    
                    fi
                else
                    /usr/sbin/nginx -t &>err.txt
                    nginx_conf=$(awk -F "[: ]" 'NR==1{print $(NF-1)}' err.txt)
                    nginx_line=$(awk -F "[: ]" 'NR==1{print $(NF)}' err.txt)
                    /usr/sbin/nginx -t
                    read -p "$nginx_conf 配置文件有错,在第 $nginx_line 行, 是否要需要进行配置修改 [y|n]: " re
                    case $re in
                        y|yes|YES)
                            vim +${nginx_line} ${nginx_conf}
                            ;;
                        n|no|NO)
                            echo "你可以选择手动修改,再见!"
                            ;;
                        *)
                            echo "USAGE: $0 {y|n} "
                    esac
                fi
            else
                action "nginx没有启动,无法完成重载" /bin/false
            fi
            ;;
        status)
            if [ -f /var/run/nginx.pid ];then
                nginx_pid=$(cat /var/run/nginx.pid)
                echo "nginx ( $nginx_pid ) is running...."
            else
                echo "nginx is Not running...."
            fi
            ;;
        *)
            echo "USAGE: $0 [ start | stop | reload | status ] "
    
    esac
    
    #解锁
    
    rm -f $Lock
    

    03. 场景示例三:实现系统管理工具箱

    [root@qiudao /scripts]# cat case-6.sh
    cat << EOF
    ################################
    h 显示命令帮助
    f 显示磁盘分区
    d 显示磁盘挂载
    m 显示内存使用
    u 查看系统挂载
    q 退出
    #################################
    EOF
    read -p "请输入你要查询的状态:" sys
    #编辑case语句
    case $sys in
        h)
            help
            ;;
        f)
            df -h
            ;;
        d)
            df -h
            ;;
        m)
            free -m
            ;;
        u) 
            w
            ;;
        q)
            exit
            ;;
        *)
            echo "请按示例输入Usage:$0 {h|f|d|m|u|q}"
    esac
    
    

    04. 场景示例四:实现简单的JumpServer

    1.执行脚本后,需要看到所有我能管理的主机2.有一个选择菜单,提示输入连接某个主机3.需要写一个死循环,保证程序连接后端服务,退出后还能接着选择主机。4.不能让跳板机直接ctrl+c ctrl+z退出了,trap 控制ctrl+c ctrl+z的信号5.退出服务器的会话,再次登录,又可以正常操作服务器。将脚本加入到/etc/bashrc中,当用户一连接,自动就运行该脚本。
    
    
    #加强版
    
    [root@qiudao /scripts]# cat jumpserver2.sh
    #!/usr/bin/
    fun(){
    cat <<EOF
    #####################################
    1 db01-172.16.1.51
    2 db02-172.16.1.51
    3 nfs01-172.16.1.31
    4 help
    5 退出
    ######################################
    EOF
    }
    fun
        trap ""HUP INT YSYP 
    while true
    do
    #请你输入想要连接的主机号
        read -p "请你输入想要连接的主机号,请输入[1|2|3]" con
        case #con in
            1)
                ssh root@172.16.1.51
                ;;
            2)
                ssh root@172.16.1.52
                ;;
            3)
                ssh root@172.16.1.31
                ;;
            4)
                clear
                fun
                ;;
            5)
                exit
                ;;
            *)
                echo "Usage: $0请输入真确的编号如[1|2|3|4|5]"
        esac
    done
    
    

    1.执行脚本后,需要看到所有我能管理的主机2.有一个选择菜单,提示输入连接某个主机3.需要写一个死循环,保证程序连接后端服务,退出后还能接着选择主机。4.不能让跳板机直接ctrl+c ctrl+z退出了,trap 控制ctrl+c ctrl+z的信号5.退出服务器的会话,再次登录,又可以正常操作服务器。将脚本加入到/etc/bashrc中,当用户一连接,自动就运行该脚本。

    05. 场景示例五:实现多级菜单功能

    [root@backup scripts]# cat funl.sh 
    #!/bin/bash
    ##############################################################
    # File Name: funl.sh
    # Time: 2019-10-20-16:59:06
    # Author: qls
    # Organization: www.increase93.com
    ##############################################################
    fun_main(){
    cat <<EOF
    ----------------main-----------------
    | 1) 安装nginx |
    | 2) 安装php |
    | 3)退出 |
    -------------------------------------
    EOF
    }
                                                                                                        
    fun_main_nginx(){
    cat <<EOF
    ----------------------nginx--------------------
    1 安准nginx1.1
    2 安装nginx1.2
    3 安装nginx1.3
    4 返回上一页
    -----------------------------------------------
    EOF
    }
    fun_main_php(){
    cat <<EOF
    ----------------------php--------------------
    1 安准php1.1
    2 安装php1.2
    3 安装php1.3
    4 返回上一页
    -----------------------------------------------
    EOF
    }
    while true
    do
        fun_main
        read -p "请输入主菜单需要选择的选项,使用方法如[1|2|3]: " fun
        case $fun in
        1)
            clear
            while true
            do
                fun_main_nginx
                read -p "请输入你需要安装nginx的版本选项如[1|2|3|4]: " dir
                case $dir in
                    1)
                        clear
                        echo "安装nginx1.1......"
                        sleep 5
                        ;;
                    2)
                        clear
                        echo "............."
                        ;;
                    4)
                        clear
                        break
                        ;;
                    esac
            done
                    ;;
        2)
            clear
            while true
            do
                fun_main_php
                read -p "请输入你需要安装php的版本选项如[1|2|3|4]: " dir1
                case $dir1 in
                    1)
                        clear
                        echo "安装php1.1......"
                        sleep 5
                        ;;
                    2)
                        clear
                        echo "............."
                        ;;
                    4)
                        clear
                        break
                        ;;
                    esac
            done
                    ;;
        3)
            exit
            ;;
        *)
            echo "Usage:[1|2|3]"
        esac
    done
    
    

    补充

    一. trap捕捉到信号之后,可以有三种反应方式:

      (1)执行一段程序来处理这一信号

      (2)接受信号的默认操作

      (3)忽视这一信号

      二. trap对上面三种方式提供了三种基本形式:

      第一种形式的trap命令在shell接收到signal list清单中数值相同的信号时,将执行双

      引号中的命令串。

      trap 'commands' signal-list

      trap "commands" signal-list

      为了恢复信号的默认操作,使用第二种形式的trap命令:

      trap signal-list

      第三种形式的trap命令允许忽视信号

      trap " " signal-list

      注意:

      (1) 对信号11(段违例)不能捕捉,因为shell本身需要捕捉该信号去进行内存的转储。

      (2) 在trap中可以定义对信号0的处理(实际上没有这个信号), shell程序在其终止(如

      执行exit语句)时发出该信号。

      (3) 在捕捉到signal-list中指定的信号并执行完相应的命令之后, 如果这些命令没有

      将shell程序终止的话,shell程序将继续执行收到信号时所执行的命令后面的命令,这样将

      很容易导致shell程序无法终止。

      另外,在trap语句中,单引号和双引号是不同的,当shell程序第一次碰到trap语句时,

      将把commands中的命令扫描一遍。此时若commands是用单引号括起来的话,那么shell不会

      对commands中的变量和命令进行替换, 否则commands中的变量和命令将用当时具体的值来

      替换。

    1) SIGHUP       2) SIGINT       3) SIGQUIT      4) SIGILL
    5) SIGTRAP      6) SIGABRT      7) SIGBUS       8) SIGFPE
    9) SIGKILL     10) SIGUSR1     11) SIGSEGV     12) SIGUSR2
    13) SIGPIPE     14) SIGALRM     15) SIGTERM     17) SIGCHLD
    18) SIGCONT     19) SIGSTOP     20) SIGTSTP     21) SIGTTIN
    22) SIGTTOU     23) SIGURG      24) SIGXCPU     25) SIGXFSZ
    26) SIGVTALRM   27) SIGPROF     28) SIGWINCH    29) SIGIO
    30) SIGPWR      31) SIGSYS      33) SIGRTMIN    34) SIGRTMIN+1
    35) SIGRTMIN+2 36) SIGRTMIN+3 37) SIGRTMIN+4 38) SIGRTMIN+5
    39) SIGRTMIN+6 40) SIGRTMIN+7 41) SIGRTMIN+8 42) SIGRTMIN+9
    43) SIGRTMIN+10 44) SIGRTMIN+11 45) SIGRTMIN+12 46) SIGRTMIN+13
    47) SIGRTMIN+14 48) SIGRTMIN+15 49) SIGRTMAX-15 50) SIGRTMAX-14
    51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
    55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6
    59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
    63) SIGRTMAX-1 64) SIGRTMAX
    
  • 相关阅读:
    Leecode no.22 括号生成
    修改mysql数据库的时区
    Django 路由层之反向解析
    学习 Django 的几个教程网址
    leetcode周赛 242
    AcWing第二次热身赛
    AcWing夏季每日一题--最长公共子序列
    AcWIng夏季每日一题--序列最大收益
    leetcode周赛 241
    第十二届蓝桥杯C++ B组
  • 原文地址:https://www.cnblogs.com/1naonao/p/11716354.html
Copyright © 2020-2023  润新知