————————————————

Linux结构化命令

结构化命令

定义

  • 可用于执行流程控制和改变执行顺序与语句

if command 语句(命令退出状态码)

  • if...then

    • if根据command命令返回码来判断是否执行,如果返回码的值为0,就执行then语句后面的代码块
   if command
     then 
      commands
   fi
  • if...then...else...

    • if 根据command命令返回码来判断是否执行,如果返回码的值为0,就执行then语句,否则,执行else后面的代码块
     if command
      then 
       commands
      else 
       commands
     fi
  • if..then...嵌套if...else...

    • if根据command命令返回码来判断是否执行,如果返回码的值为0,就执行then语句后面的代码块,然后再在then后面再判断具体的条件是否成立,如果成立就执行具体操作,否则,执行else后面的代码块
     if command
      then 
        if  conditon
            commands
        fi
      else 
       commands
     fi
  • if...then...elif..then..else

    • if根据command命令返回码来判断是否执行,如果返回码是0,就执行then语句后面的代码块;否则,则判断elif后面的命令,如果条件成立,执行then后面的命令;如果以上都不满足,则执行else后面的代码块
     if command1
       then 
        commands
     elif command2
       then 
        more commands
     fi 

if [ conditon ]语句(=if test conditon语句)

  • condition

    • 字符串比较

      • 字符相等性比较

        =
        !=

      • 字符顺序比较

        str1 \> str2

        str1 \< str2

        • 注意事项

          • >在字符比较中容易当成重定向,需要加转义符

          • 字符比较大小是按照ascii码来比较

          • sort排序是使用系统本地设置的语言排序方法,而此处字符比较则是使用ascii

      • 字符空值判断

        -n(=not empty)
        -z(=empty)

    • 数值比较

     -gt(greater than)
     -lt(less than)
     -eq(equal)
     -ge(greater than)
     -le(less than)
     -ne(not equal
  • 注意事项
    • bash shell文件中,浮点数不能比较
  • 文件比较

    • 是否存在目录

      • -d
    • 是否存在文件

      • -f
    • 是否存在目录或文件

      • -e
    • 是否可读

      • -r
    • 文件是否为非空

      • -s
    • 是否可写

      • -w
    • 是否可执行

      • -x
    • 是否为属主

      • -O
    • 属组是否为默认组

      • -G
    • 是否新于

      • -nt
    • 是否旧于

      • -ot
    • 是否有数据

      • -n

复合条件语句

  • 使用布尔来组合判断

    • 与运算

      [ condition1 ] && [ conditon2 ]

    • 或运算

      [ condition1 ] || [ condition2 ]

if...then高级表达

  • 使用双圆括号来进行数学运算

    if (( expression));then

  • 使用双方括号来进行字符运算

    if [[ expression]];then

    • 注意事项

      • expression中字符匹配支持通配符

case语句

  • 可避免重复使用if语句判断某个变量的值,而是采用列表的形式检查单个变量多个可能值
  • 语法
    case variable in 
    pattern1 | pattern2) commands1;; 
    pattern3) commands2;; 
    *) default commands;; 
    esac 
  • 如果variable的值等于pattern的值,则执行pattern指定的命令
  • 最后的pattern的*号代表其他的情况
  • 命令的开始是case,结束则是单词的倒写esac

注意事项

  • 方括号是与test命令同义的特殊bash命令,即if [conditon] 等同于 if test conditon
  • if [condtion]如果为true,会为if语句产生退出状态码0,如果为false,会为if语句产生非零退出状态码
posted @ 2022-10-16 21:50  Tjane'Blogs  阅读(45)  评论(0)    收藏  举报