BASH: [] (test) behaves incorrectly

In my bash testthere is a relation to exit with status 0:

$ test -n && echo true || echo false
-> true

and

$ test -n "" && echo true || echo false
-> false

This means that if it takes no arguments at all, it takes a nonzero value.

The case -zworks correctly:

$ test -z && echo true || echo false
-> true
$ test -z "" && echo true || echo false
-> true

Is this the expected behavior?

+5
source share
3 answers

Basically, you ask if the string "-z" is not empty. It is, therefore, it informs you true. The actual algorithm uses:

  • 0 arguments:

    Exit from the false (1).

  • 1 argument:

    Exit true (0) if $ 1 is not null; otherwise, exit false.

  • 2 arguments:

    $1 '!', true, $2 - null, false, $2 .

    $1 , true, true, false .

    .

...

POSIX.

+5

, "-n" "-z" , , test "a non-empty string" - true. , test , count 1, .

+1

, .

$ man test
-n string                   True if the length of string  is
                             non-zero.
-z string                   True if  the  length  of  string
                             string is zero.

test [option] #without any operand , .

:

test -d
test -f
test -n
test -G
test -k
...
0

All Articles