shell脚本:测试语句以及判断语句

shell编程基础:测试语句以及判断语句

标签:shell脚本

  • 测试
    在shell脚本中,测试单独成为一种结构。有两种测试结构:

    1. test exprsssion
    2. [ expression ]
        为增加代码的可读性,推荐使用第二种方式(注意空格),而且这种方式更容易与if、case、while这些条件判断的关键字连用。
      【举例】

      • 文件测试
        使用文件测试的方法测试该文件“是否存在”,只需要使用-e操作符即可。
      [root@localhost ~]# test -e /var/log/messages
      [root@localhost ~]# echo $?
      
      0
      [root@localhost ~]# [ -e /var/log/messages ]
      [root@localhost ~]# echo $?
      0

    文件测试符:
    shell脚本:测试语句以及判断语句_第1张图片
    shell脚本:测试语句以及判断语句_第2张图片
    【补充】FILE1 -nt FILE2中的-nt是newer than的意思,而FILE1 -ot FILE2中的ot是older than的意思。文件新旧比较的主要使用场景是判断文件是否被更新或增量备份。

    • 字符串测试
      字符串测试符:
      shell脚本:测试语句以及判断语句_第3张图片
      比如:

      
      #比较str1和str1的大小,需要注意的是,>和<;都需要进行转义
      
      [root@localhost ~]# [ "$str1" \> "$str2" ]
      
      #如果不想用转义符,则可以用[[]]括起表达式(注意!!!)
      
      [root@localhost ~]# [[ "$str1" > "$str2" ]]
    • 整数测试
      整数测试符:
      shell脚本:测试语句以及判断语句_第4张图片
      比如(注意双引号的局部引用作用):
      [root@localhost ~]# [ "$num1" -eq "$num2" ]

    • 逻辑测试符和逻辑运算符
      逻辑测试符:

      比如:
      [root@localhost ~]# [ -e /var/log/messages -a -e /var/log/messages01 ]
      逻辑运算符:

      [root@localhost ~]# [ -e /var/log/messages ] && [ -e /var/log/messages01 ]
      比如:

      ```
      #逻辑与运算
      expression1 && expression2 && expression3
      #逻辑与测试
      [ expression1 -a expression2 -a expression3 ]
      ```
      
      有趣的:
      一个隐形的if-then-else语法
      

      expression && DoWhenExpressionTrue || DoWhenExpressionFalse

  • 判断

    • if判断结构(注意分号
    if expression; then           
        command
    fi

    如果要执行的不止一条命令,则不同命令间用换行符隔开,如下所示:

    if expression; then             
        command1
        command2
        ...
    fi
    • if else判断结构
    if expression; then        
        command
    else    
        command
    fi
    if expression1; then              
        command1
    elif expression2; then
        Command2
    elif expression3; then 
        Command3...
    fi
    • case判断结构
    case VAR in
    var1) command1 ;;
    var2) command2 ;;
    var3) command3 ;;
    ...
    *) command ;;
    esac

    case判断结构中的var1、var2、var3等这些值只能是常量或正则表达式

你可能感兴趣的:(编程,shell,脚本)