Why Isn’t [ -n ] False Like [ -n “” ] in Bash?

bash

My question is on return values produced by this code:

if [ -n ]; then echo "true"; else echo "false"; fi

This prints true.

Its complementary test using [ -z ] also prints true:

if [ -z ]; then echo "true"; else  echo "false"; fi

In the above code, why does the [ -n ] test assume the string value that is not passed at all, as not null?

The code below prints false. This is expected since the passed string value is null and of zero length.

if [ -n "" ]; then echo "true"; else  echo "false"; fi

Best Answer

[x] is equivalent to [ -nx] even if x starts with - provided there is no operand.

$ [ -o ] ; echo $?
0
$ [ -eq ] ; echo $?
0
$ [ -n -o ] ; echo $?
0
$ [ -n -eq ] ; echo $?
0
Related Question