1

If there are spaces around the operator, test returns the correct value of the expression.

But if there are no spaces, it doesn't throw any syntax error and always return true.

$ test "A" == "A"; echo $?
0 #<-- OK, 0 stands for true
$ test "A" == "B"; echo $?
1 #<-- OK, 1 stands for false
$ test "A"=="A"; echo $?
0 #<-- OK, 0 stands for true
$ test "A"=="B"; echo $? 
0 #<-- ??? should either return 1 (false), or throw a syntax error (exit code > 1)
  • 1
    nitpick, the == operator isn't standard, so you might want to use = instead for compatibility with all shells. – ilkkachu Oct 28 '22 at 10:48

1 Answers1

3

That's because the syntax isn't wrong: test "A"=="B" is the same as test foo, it is testing a string and since the string isn't empty, it is returns true. This is explained in the test section of man bash:

test and [ evaluate conditional expressions using a set of rules based on the number of arguments.

  • 0 arguments

    The expression is false.

  • 1 argument

    The expression is true if and only if the argument is not null.

Arguments are defined by whitespace, so since there is no space around the ==, the entire string "A"=="B" is parsed as a single argument.

And here it is in action:

$ test foo; echo $?
0
$ test ""; echo $?
1

As you can see above, passing an empty string will return false, but passing a non-empty string returns true.

terdon
  • 242,166