• shell脚本的条件测试与比较


    shell脚本的条件测试

    1、test

    格式:test <测试表达式>

    [root@hxjk_test_backend_services test]# ls
    aa.sh  bb.sh  cc.sh
    [root@hxjk_test_backend_services test]# cat cc.sh
    test -f aa.sh && echo true || echo false
    test -f aaa.sh && echo true || echo false
    test -z "$1" && echo true || echo false
    [root@hxjk_test_backend_services test]# sh cc.sh 
    true
    false
    true
    [root@hxjk_test_backend_services test]# sh cc.sh 123
    true
    false
    false
    [root@hxjk_test_backend_services test]# 
    

    test -f : 测试文件存在且为普通文件

    test -z : 测试字符串长度为0

    test命令执行成功(为真)则执行&&后面的命令,失败(为假)执行||后面的命令。

    2、[](中括号)

    格式:[ <测试表达式> ],和test等价,即test的所有判断选项都可以直接在[]里使用。

    [root@hxjk_test_backend_services test]# ls
    aa.sh  bb.sh  cc.sh  dd.sh
    [root@hxjk_test_backend_services test]# cat dd.sh
    [ -f aa.sh ] && echo true || echo false
    [ -f aaa.sh ] && echo true || echo false
    [root@hxjk_test_backend_services test]# sh dd.sh
    true
    false
    [root@hxjk_test_backend_services test]# 
    

    3、[[]]

     格式:[[ <测试表达式> ]],属于[]和test命令的扩展命令,功能更丰富也更复杂。

     文件测试表达式

    字符串测试表达式

    常用字符串测试操作符

    1. -n "字符串" : 若字符串的长度为0,则为真,即测试表达式成立,n可以理解为no zero.字符串一定要加双引号.

    2. -z “字符串”: 若字符串的长度为0,则为震,即测试表达式成立,z可以理解为zero 的缩写.

    3. "串1"="串2": 若字符串1等于字符串2,则为真,可使用"==" 代替"=". 比较符号两端一定要有空格.

    4. "串1"!="串2": 不等于. 比较符号两端一定要有空格.

    [root@hxjk_test_backend_services test]# cat ee.sh
    [ -n "$1" ] && echo 1 || echo 0
    [ -n "$2" ] && echo 1 || echo 0
    
    [root@hxjk_test_backend_services test]# sh ee.sh "123" ""
    1
    0
    [root@hxjk_test_backend_services test]#
    

    整数二元比较操作符

     

  • 相关阅读:
    20210621SMB1协议安全问题
    用Markdown编辑微信公众号
    重温数据结构01 基本概念
    Mac安装HomeBrew
    曲終
    四、10分钟ToPandas_0.24.2
    三、Pandas速查手册中文版
    一、Numpy库与多维数组
    零.注意的细节
    二、Pandas库与数据处理
  • 原文地址:https://www.cnblogs.com/gexiaoshan/p/9854989.html
Copyright © 2020-2023  润新知