shell脚本字符串相关

  1. 字符串比较
  • 字符串相等比较

    相等:在[]中使用==或=

    [root@master Workspace]# ./test.sh 
    true
    [root@master Workspace]# cat test.sh 
    #! /bin/sh
    
    a="test"
    
    if [ "$a" = "test" ];then
        echo "true"
    fi
    # or
    [root@master Workspace]# ./test.sh 
    true
    [root@master Workspace]# cat test.sh 
    #! /bin/sh
    
    a="test"
    
    if [ "$a" == "test" ];then
        echo "true"
    fi
    
    

    不等:在[]中使用!=

    [root@master Workspace]# cat test.sh 
    #! /bin/sh
    
    a="test"
    
    if [ "$a" != "test" ];then
        echo "true"
    fi
    [root@master Workspace]# ./test.sh 
    
    
  • 字符串包含

    在[[ ]]中使用=~

    [root@master Workspace]# ./test.sh 
    true
    [root@master Workspace]# cat test.sh 
    #! /bin/sh
    
    a="test"
    
    if [[ "$a" =~ "es" ]];then
        echo "true"
    fi
    
    

    不包含

    [root@master Workspace]# cat test.sh 
    #! /bin/sh
    
    a="test"
    
    if [[ ! "$a" =~ "es" ]];then
        echo "true"
    fi
    
    
  • 模式匹配

    [root@master Workspace]# cat test.sh 
    #! /bin/sh
    
    a="test"
    # 以t开头
    if [[  "$a" == t* ]];then
        echo "true"
    fi
    [root@master Workspace]# ./test.sh 
    true
    
    

    shell脚本#为注释符号,那么如何判断以#开头呢?

    [root@master Workspace]# ./test.sh 
    true
    [root@master Workspace]# cat test.sh 
    #! /bin/sh
    
    a="#test"
    
    if [[  "$a" == ''#*'' ]];then
        echo "true"
    fi
    # or 
    [root@master Workspace]# ./test.sh 
    true
    [root@master Workspace]# cat test.sh 
    #! /bin/sh
    
    a="#test"
    
    if [[  "$a" == \#* ]];then
        echo "true"
    fi
    
    
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容