开发者

String comparison doesn't work

开发者 https://www.devze.com 2023-03-12 13:49 出处:网络
For some reason this script prints \"string are equal\" #!/bin/bash A=\'foo\' B=\'bar\' if [ $A=$B ]; then

For some reason this script prints "string are equal"

#!/bin/bash
A='foo'
B='bar'

if [ $A=$B ];
then
  echo开发者_如何学Python 'strings are equal' 
fi

What am I doing wrong?


You have to leave a space around the equal sign:

if [ "$A" = "$B" ];
then
  echo 'strings are equal' 
fi

Edit: Please notice also the quotation marks around the variables. Without them you will get into trouble if one of them is empty.

Otherwise the test is interpreted as test if the string "foo=bar" has a length>0.
See man test:

   ...
   STRING equivalent to -n STRING
   -n STRING
          the length of STRING is nonzero
   ...


You're supposed to have spaces around the equals character:

if [ $A = $B ];
       ^ ^
      There

Also, you ought to quote the variables, like this:

if [ "$A" = "$B" ];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号