zoukankan      html  css  js  c++  java
  • 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)

  • 相关阅读:
    广商博客冲刺第六七天new
    广商博客沖刺第一天(new ver):
    20150529项目之典型用户与场景
    冲刺第二,三,四,五,六天
    冲刺第一天:
    Android 學習之旅!(2)
    20150512 作业6 团队项目之需求
    Android 學習之旅!(1)
    20150421 作业5 四则运算 测试与封装 5.1 5.2(doing)
    20150421 作业5 四则运算 测试与封装 5.1
  • 原文地址:https://www.cnblogs.com/caiyao/p/4658202.html
Copyright © 2011-2022 走看看