#!/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)