Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does 'test -n' return 'true' in bash?

Tags:

bash

I was wondering how comes

test -n

return 'true', for example :

if test -n; then echo "yes" ; else echo "no" ; fi

prints "yes", even though test was given, theoretically, an empty-length string as an argument along with the option -n, which checks whether the string length is 0 (returns false) or something else (returns true).

Thank you

like image 718
Biganon Avatar asked Feb 24 '23 16:02

Biganon


2 Answers

From the documentation:

The test and [ builtins 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.

In your case you simply have one non-null argument (-n).

like image 130
Paŭlo Ebermann Avatar answered Mar 07 '23 21:03

Paŭlo Ebermann


It returns true for the same reason test x returns true - the string -n is non-empty. It is not exercising the -n option because -n requires a second argument and you've not provided one.

test -n  ""  || echo false
x=""
test -n  $x  && echo true
test -n "$x" || echo false

Each echo command is executed; note, in particular, the middle one!

like image 23
Jonathan Leffler Avatar answered Mar 07 '23 21:03

Jonathan Leffler