Bash – “test -n && echo not empty” prints “not empty”. Is that expected behaviour

bashtest

When I execute the following line

test -n && echo not empty

it prints "not empty". This occurs when you have an empty variable, and test for non-emptyness while forgetting to quote the value:

VAR=
test -n  $VAR  && echo wrong 1
test -n "$VAR" && echo wrong 2

Is this expected behaviour?

Best Answer

Yes, this is expected behaviour. When only one argument is passed to test, a length check is performed. From 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.

That is, essentially it is the equivalent of test foo, but using -n as the string.

Related Question