Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH: [ ] (test) behaves unconformly

Tags:

linux

bash

gnu

In my bash test has an attitude to exit with status 0:

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

while

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

It means when it doesn't receive any argument at all, it assumes nonzero.

The case -z works properly instead:

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

Is this the expected behavior?

like image 816
davide Avatar asked Oct 25 '11 13:10

davide


1 Answers

Basically, you are asking test whether the string "-z" is nonempty. It is, so it tells you true. The actual algorithm test uses is:

  • 0 arguments:

    Exit false (1).

  • 1 argument:

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

  • 2 arguments:

    If $1 is '!', exit true if $2 is null, false if $2 is not null.

    If $1 is a unary primary, exit true if the unary test is true, false if the unary test is false.

    Otherwise, produce unspecified results.

...

Quoted from the POSIX test command specification.

like image 173
jpalecek Avatar answered Sep 28 '22 00:09

jpalecek