zoukankan      html  css  js  c++  java
  • shell脚本(8)-流程控制if

    一、单if语法

    1、语法格式:

    if [ condition ]  #condition值为
      then
        commands
    fi

    2、举例:

    [root@localhost test20210725]# vim document.sh
    
    #!/usr/bin/bash
    
    #假如没有/tmp/abc这个文件夹,就创建一个
    
    if [ ! -d /tmp/abc ]
       then
          mkdir -pv /tmp/abc
      echo "文件创建成功"
    fi

    查看运行结果:

    [root@localhost test20210725]# sh document.sh 
    mkdir: created directory ‘/tmp/abc’
    文件创建成

    二、if...else语法

    1、语法格式:

    if [ condition ]  #condition值为
       then
          commands1
    else
          commands2   
    fi

    2、举例:

    [root@localhost test20210725]# vim document2.sh 
    
    #!/usr/bin/bash
    
    #假如没有/tmp/abc这个文件夹,就创建一个,否则打印信息
    
    if [ ! -d /tmp/abc ]
       then
          mkdir -pv /tmp/abc
          echo "文件创建成"
    else
          echo "文件已经存在,不再创建"     
    fi

    查看运行结果:

    [root@localhost test20210725]# sh document2.sh 
    mkdir: created directory ‘/tmp/abc’
    文件创建成
    [root@localhost test20210725]# sh document2.sh 
    文件已经存在,不再创建

    三、if...elif...else语法

    1、语法格式:

    if [ condition1 ]  #condition值为
       then
          commands1
    elif [ condition2 ]
    then
    commands2
    ......
    else commandsx fi

    2、举例说明:

    [root@localhost test20210725]# vim number3.sh
    
    #!/usr/bin/bash
    
    #脚本传递两个数字参数并比较
    if [ $1 -eq $2 ]
       then
          echo "$1 = $2"
    elif [ $1 -gt $2 ]
       then
          echo "$1 > $2"
    else
          echo "$1 < $2"
    fi

    查看运行结果:

    [root@localhost test20210725]# sh number3.sh 1 1
    1 = 1
    [root@localhost test20210725]# sh number3.sh 2 1
    2 > 1
    [root@localhost test20210725]# sh number3.sh 1 3
    1 < 3

    四、if高级语法

    1、使用(())植入数学表达式做运算,举例:

    [root@localhost test20210725]# vim if_avg.sh
    
    #!/usr/bin/bashif (( 100%3+1>1  ))
      then
        echo "yes"
    else
        echo "no"
    fi

    查看运行结果:

    [root@localhost test20210725]# sh if_avg.sh 
    yes

    2、使用[[]]可以在条件中使用通配符,举例:

    [root@localhost test20210725]# vim if_avg2.sh
    
    #!/usr/bin/bash
    
    for i in r1 rr2 cc rr3
      do
        if [[ $i == r* ]];then
          echo $i
        fi
    done

    查看运行结果:

    [root@localhost test20210725]# sh if_avg2.sh 
    r1
    rr2
    rr3
  • 相关阅读:
    Android中onBackPressed()的使用
    Python初次学习
    svn Mac下面无法更新png
    UIView的layoutSubviews和drawRect
    "_deflate", referenced from: -[NSData(NSDataAdditions) gzipDeflate] in NSDataAdditions.o
    Error12
    pods安装
    xib为view添加边框
    这些机型将被淘汰
    Development cannot be enabled while your device is locked.
  • 原文地址:https://www.cnblogs.com/mrwhite2020/p/15017984.html
Copyright © 2011-2022 走看看