• Shell编程--流程控制


    1.条件结构

    测试:test 条件
            条件为真返回 0,条件为假返回 1
    语法:[ 条件 ]
    test 条件能够理解以下类型的表达式

    1.1.文件测试(字符串)

    -n STRING
    the length of STRING is nonzero
    -n 字符串的长度 【不是】零成功。

    ​-n不为空案例:

    [root@localhost ~]# vim a.sh
    #!/usr/bin/bash
    read -p "请输入幸运数字" lucky_num
    if [[ -n $lucky_num ]]; then
            echo "您的幸运数字是$lucky_num"
    else
            echo "您输入的幸运数字为空"
            exit
    fi
    //执行:
    [root@localhost ~]# bash a.sh
    请输入幸运数字12
    您的幸运数字是12
    [root@localhost ~]# bash a.sh
    请输入幸运数字
    您输入的幸运数字为空
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    -z STRING
            the length of STRING is zero
    -z 字符串长度【是】零成功
    对于未定义或赋予空值的变量将是为空串。

    -z为空案例,为空时则执行

    [root@localhost ~]# cat b.sh
    #!/usr/bin/bash
    read -p "请输入幸运数字" lucky_num
    if [[ -z $lucky_num ]]; then
            echo "您输入的幸运数字为空"
    else
            echo "您输入的幸运数字为$lucky_num"
            exit
    fi
    //执行:
    [root@localhost ~]# bash b.sh
    请输入幸运数字         #不输入,留空
    您输入的幸运数字为空
    [root@localhost ~]# bash b.sh
    请输入幸运数字23       #输入数字
    您输入的幸运数字为23
    
    [root@localhost ~]# vim string.sh
    #!/bin/bash
    while :
    do
            read -p "请输入你的密码:" pass
            passwd=12345
            if [[ -z $pass ]];then
                    echo "您输入的密码不能为空"
                    exit 1
            else
                if [[ $pass == $passwd  ]];then
                    echo  "密码输入成功"
                    break
                else
                    echo "您输入的密码有误,请重新输入"               
                fi
            fi
    done
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    1.2.字符串比较

    STRING1 = STRING2 (等于)
            the strings are equal
    STRING1 != STRING2 (不等于)
            the strings are not equal

    1.3.数字条件比较

    格式含义
    -eq(equal)等于
    -ne(not equal)不等于
    -ge(Greater than or equal to)大于等于
    -le(Less than or equal to)小于等于
    -gt(greater than)大于
    -lt(less than)小于

    1.4.文件条件判断

    格式含义
    -f存在且是正规文件
    -d存在且是目录
    -h存在且是符号链接
    -b块设备
    -c字符设备
    -e文件存在
    [root@localhost ~]# vim file.sh
    #!/bin/bash
    file=/root/test.txt
    if [[ -e $file ]];then
            echo "$file"
    else
            echo "文件不存在"  
            touch $file &&  echo "文件已创建"
    fi
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    2.if多条件判断

    流程控制:在一个shell脚本中的【命令执行的顺序】称作脚本的流。大多数脚本会根据一个或多个条件来改变它们的流。
    流控制命令:能让脚本的流 根据条件而改变的命令,称为条件流控制命令
    exit语句:退出程序的执行,并返回一个返回码,返回码为0正常退出,非0为非正常退出,例如: exit 0
    条件判断语法:​if 代码返回0表示真,非0为假

    if语句语法如下:
    if [[ -e -eq -ne ]];then  //-e -eq -ne是你的测试条件,你要测试什么,对什么内容做判断(例如$? -eq 0)
        list1                 //执行list2里面的内容
    elif [[ -e -eq ]];then    //接着在怎么做。(多条件判断)
        list2
    else                      //如果前面的命令没有执行成功那就执行else下面的命令。
        list3
    fi
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    [root@localhost ~]# cd /opt/test/script/
    [root@localhost script]# vim testif.sh
    #!/bin/bash
    read -p "请输入号码: " num 
    if [[ $num = 1 ]];then
        echo "1"
    elif [[ $num = 2 ]];then
        echo "2"
    elif [[ $num = 3 ]];then
        echo "3"
    else 
        echo "输入有误!"
    fi
    [root@localhost script]# bash testif.sh
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    例:脚本if.sh,必须在脚本后加上适当的参数脚本才能正确执行

    [root@localhost script]# vim if.sh
    #!/bin/bash
    if [[ "$1" = "hello" ]]; then
        echo "Hello! How are you ?"
    elif [[ "$1" = "" ]]; then
        echo "You MUST input parameters"
    else
        echo "The only accept parameter is hello"
    fi
    [root@localhost script]# chmod +x if.sh
    //测试:
    [root@localhost script]# ./if.sh 
    [root@localhost script]# ./if.sh hello
    [root@localhost script]# ./if.sh 434
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    ​练习:
    (1)检测nginx是否已经安装、已经运行,如果没有安装和运行则【安装并启动】,并【记录启动】的时间,保存到日志中。

    #!/bin/sh
    #check_nginx_install
    nginx -V
    if [[ $? -ne 0 ]]; then
            yum -y install nginx
    fi
    #check_nginx_status
    ps -ef|grep nginx && netstat -ntlp|grep nginx
    if [[ $? -ne 0 ]]; then
            systemctl restart nginx 
    fi
    #record_nginx_up_time
    up_time=$(systemctl status nginx.service |grep -i active|awk '{print $6,$7}')
    echo $up_time > /root/nginx_up_time
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    (2)测试ip地址主机位从2到100的机器是否存活,并把存活的机器记录到文本文件alivehost.txt内。(使用ping命令)

    #!/usr/bin/bash
    ip=192.168.17
    for i in {2..100}
    do
       ping -c1 -w1 $ip.$i &> /dev/null
       if [ $? -eq 0 ];then
            echo "$ip.$i is up" >> activehost.txt
       else
            echo "$ip.$i is down" &> /dev/null
       fi
    done
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    多个条件联合:

    &&:逻辑与,前面执行成功,后面才执行。前面命令执行失败,后面命令也不执行
    if [ $condition1 ] && [ $condition2 ];then
    if [[ $condition1 && $condition2 ]];then

    ||:逻辑或,前面执行失败,后面执行,前面命令执行成功,后面不执行。
    if [ $condition1 ] || [ $condition2 ];then
    if [[ $condition1 || $condition2 ]];then

    拓展知识:[[ ]]和[ ]的区别

    [[ ]]支持正则表达式,而[ ]不支持
    例如:
          [[ $a == z* ]] # 正则匹配
          [ $a == z* ] # 无效
    [ ] 语法 都可以由 [[ ]] 替代,并且后者功能更丰富
    [ ] 使用 -a、-o 分别表示与、或 关系 ,[[ ]]使用 &&、 ||表示与 、或关系
    而且在使用中,[[ ]]比[ ]更加的稳定,在脚本的使用中,建议使用[[ ]]

    1. 判断一个用户是否存在
    2. 判断当前内核主版本是否为3,且次版本是否大于10
        //主版本获取:
        uname -r|cut -d. -f1    #-d.    以什么为分隔符 -f1打印第一段
        3
        //次版本获取
        uname -r|cut -d. -f2
        10//或者:
        [root@localhost ~]# uname  -r|awk -F'.' '{print $1}'
        3
        [root@localhost ~]# uname  -r|awk -F'.' '{print $2}'
        10
    3. 判断vsftpd软件包是否安装,如果没有则自动安装 (yum是否能用,不能用自动修复,安装完成测试下,是否能用。)
    4. 判断httpd是否运行
    5. 判断指定的主机是否能ping通,必须使用$1变量
    ping -c1 -w1 $1.com
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    3.case语句

    case 语句是 shell 中流控制的第二种方式,语法如下:
    case $变量 in
         pattern1)
              list1
              ;;          //2个英文的分号结尾。
         pattern2)
              list2
              ;;
         ... ...
         patternN)
              listN
             ;;
        *)                //如果前面命令没有执行成功那么执行下面这个
             list*
             ;;
    esac        //结尾
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    ​第一行:声明case关键字调用case语法,紧跟的“变量”一般为用户的输入值, in代表从下方的各个模式进行匹配
    第2-4行:匹配到“pattern1”后进行命令的输出或执行, pattern1: 一般为字符或数值
    第11-12行:当用户输入的字符不存在匹配模式时, 直接执行或打印
    )下的命令或语句
    *

    [root@localhost script]# vim case1.sh
    #!/usr/bin/env bash
    case $1 in
            a)
            echo "one"
            ;;
            b)
            echo "two"
            ;;
            *)
            echo "Usage:$0 '{a|b}'"    # $0就是这个脚本
            ;;
    esac
    ​//执行结果
    [root@localhost ~]# bash case.sh
    Usage:case.sh '{a|b}'
    [root@localhost ~]# bash case.sh a
    one
    [root@localhost ~]# bash case.sh b
    two
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    练习:
    建立脚本case2.sh,当执行时,要求我们在键盘输入适当的值(数字),当输入正确时并打印,当输入错误时会提示你,应该输入正确的值。

    [root@localhost script]# vim case3.sh
    #!/usr/bin/env bash
    read -p "请输入:" get
    case $get in
    [0-9][0-9])
        echo -e "你输入的是数字,为:$get\n"
        ;;
    *)
        echo -e "你输入的不是数字。\n"
        ;;
    esac
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    示例:编写系统工具脚本

    [root@localhost script]# vim system_tools.sh
    #!/usr/bin/env bash
    #cat <<-EOF
    echo '
    +-------------------------------------------------------------------------+
    |                             System_tools V1.0                           |
    +-------------------------------------------------------------------------+
    |                     a. Stop And Disabled Firewalld.                     |
    |                     b. Disabled SELinux Secure System.                  |
    |                     c. Install Apache Service.                          |
    |                     d. Quit                                             |
    +-------------------------------------------------------------------------+
    '
    #EOF
    read -t 60 -p "请在1分钟内作出选择"  choose
    case "$choose" in
            "a")
            systemctl stop firewalld && systemctl disable firewalld
                    ;;
            "b")
                    setenforce 0
                    ;;
            "c")
                    yum -y install httpd httpd-tools
                    ;;
            "d")
                    exit
                    ;;
            *)
                    printf "请按照上方提供的选项输入!!!\n"
                    ;;
    esac
    [root@localhost script]# chmod +x system_tools.sh
    [root@localhost script]# ./system_tools.sh
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    练习:
    建立脚本service.sh,当用户执行的时候要求输入(1、2、3、4、5)时安装对应的httpd、vim、wget、更换aliyun yum源等功能,当输入错误时会提示你,应该输入正确的值。

    [root@localhost ~]# vim service.sh
    #!/bin/bash
    echo '
    +-------------------------------------------------------------------------+
    |                             System_tools V1.0                           |
    +-------------------------------------------------------------------------+
    |                     1. Install Apache Service.                          |
    |                     2. Install Vim.                                     |
    |                     3. Install Wget.                                    |
    |                     4. Change Aliyun Yum.                               |
    |                     5. Change Tencent Yum.                              |
    |                     6. Quit                                             |
    +-------------------------------------------------------------------------+
    '
    read -t 60 -p "请在1分钟内作出选择"  choose
    case "$choose" in
            "1")
                    yum -y install httpd httpd-tools
                    ;;
            "2")
                    yum -y install vim
                    ;;
            "3")
                    yum -y install wget
                    ;;
            "4")
                    yum -y install wget
                    mv /etc/yum.repos.d/* /tmp
                    wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
                    wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
                    yum makecache
                    yum repolist
                    ;;
            "5")
                    yum -y install wget
                    mv /etc/yum.repos.d/* /tmp
                    wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.cloud.tencent.com/repo/centos7_base.repo
                    wget -O /etc/yum.repos.d/epel.repo http://mirrors.cloud.tencent.com/repo/epel-7.repo
                    yum makecache
                    yum repolist
                    ;;
            "6")
                    exit
                    ;;
            *)
                    echo -e "请按照上方提供的选项输入!!!\n"
                    ;;
    esac
    
    [root@localhost ~]# bash service.sh
    +-------------------------------------------------------------------------+
    |                             System_tools V1.0                           |
    +-------------------------------------------------------------------------+
    |                     1. Install Apache Service.                          |
    |                     2. Install Vim.                                     |
    |                     3. Install Wget.                                    |
    |                     4. Change Aliyun Yum.                               |
    |                     5. Change Tencent Yum.                              |
    |                     6. Quit                                             |
    +-------------------------------------------------------------------------+
    请在1分钟内作出选择 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
  • 相关阅读:
    做数据产品半年后的体会总结
    【vue】全局组件
    剑指offer-字符串总结
    JVM的概念、内存区域
    element ui,node-sass 安装出错,绝对能解决
    linux常用命令及解释大全(二)
    黑豹程序员-架构师学习路线图-百科:MVC的演变终点SpringMVC
    rpm安装gitlab
    web框架之路由列表及SQL语句查询数据库数据替换模板变量
    【语音识别入门】概述
  • 原文地址:https://blog.csdn.net/m0_62396418/article/details/134348466