• Shell编程中括号判断中赋值语句和判断语句


    #!/bin/bash
    
    declare var="xxx" 
    # without space and use one = 
    #1.judge whether the assignment statement returns true
    echo "----------------------test assignment in bracket --------------------------------"
    [ var="yyyy" ] && echo "success"
    echo "end"
        # success
    [ "$var"="yyyy" ] && echo "success"
    echo "end"
        # success
    [ "var"="yyyy" ] && echo "success"
    echo "end"
        # success
    [ var1="yyyy" ] && echo "success"
    echo "end"
        # success
    
    # result: yes
    
    #2. judge the assignment whether be taken in bracket
    echo "--------------------test assignment whether been taken -----------------------"
    [ var="yyyy" ] && echo "$var"
    echo "end"
        #xxx
        #end
    #result: assignment can't be taken in bracket
    
    #3. whether the effect of single = and double = similary
    echo "-------------------test single = and double = ------------------------"
    [ "$var" == "yyyy" ] && echo "$var"
    echo "end"
        #end
    [ "$var" = "yyyy" ] && echo "$var"
    echo "end"
        #end
    var="yyyy"
    [ "$var" == "yyyy" ] && echo "$var"
    echo "end"
        #yyyy
        #end
    [ "$var" = "yyyy" ] && echo "$var"
    echo "end"
        #yyyy
        #end
    # result: effect same
    #4. whether the effect of having space and not space similary
    echo "----------------------test space -------------------------------------"
    [ "$var"=="yyyy" ] && echo "$var"
    echo "end"
        #yyyy
        #end
    [ "$var"=="zzzz" ] && echo "$var"
    echo "end"
        #yyyy
        #end
    #result: always true with no space 
    
    
    
    
    
    #conclusion:
    # with space at both side of = will judge in normal
    # don't space at both side of = or ==  will always true 

    通过上面的测试得出的结论是:

    在中括号判断中不使用空格例如  "$var"="xx" 或 "$var"=="xxx"(在= 和== 两边没有空格)则这个判断一直是真

    在中括号中使用空格 例如  "$var" = "xx" 或 "$var" == "xxx"(在= 和== 两边有空格) 则这个判断会按照正常的值进行判断,值相等返回true否则返回false

    可能会因使用的shell及其版本不同而导致结果不同,我使用的shell是:GNU bash, version 4.1.2(1)-release (i686-redhat-linux-gnu)

  • 相关阅读:
    如何仅仅修改每一页的页眉
    resize
    Linux搭建深度学习环境
    Image.open、cv2.imread
    any、all
    cookie
    any、all
    库文件
    出来混总要还的,要提醒自己提高核心竞争力
    “行百里者半九十”(现在才逐渐真正理解这些道理)
  • 原文地址:https://www.cnblogs.com/caiyao/p/4658202.html
Copyright © 2020-2023  润新知