5

From man test:

       ! EXPRESSION
              EXPRESSION is false

and

       -n STRING
              the length of STRING is nonzero

       STRING equivalent to -n STRING

       -z STRING
              the length of STRING is zero

So [ "$x" ] has the same effect as [ -n "$x" ] (that's explicitly stated above) and implicitly, [ ! "$x" ] has the same effect as [ -z "$x" ]. So why would one choose to use -n or -z when arguably the other forms are clearer? Is it just personal preference or am I missing an important distinction?

I've seen other questions (e.g. this one) about this but nothing to say for definite if they're functionally identical. I did wonder whether I could avoid quoting $x if I used -n or -z but if $x contains a space, this fails as with the other methods.

IpsRich
  • 797
  • 10
  • 23

1 Answers1

9

Is there an advantage to using the -z test in bash?

No.

why would one choose to use -n or -z when arguably the other forms are clearer?

Because it is arguable which form is "clearer"...

Of course -n and -z are better, because -z is like "Zero" and -n is like "Nonzero" or "Nonempty", it's easier for me to read it. [ -n "$x" ] is "if $x is Nonzero". I recommend* -n and -z.

Is it just personal preference

Yes.

am I missing an important distinction?

No.

In Bash prefer [[, if you do not need POSIX compatibility.

I did wonder whether I could avoid quoting $x if I used -n or -z

No. You can avoid quoting if you use [[. I recommend* quoting every expansion anyway to get used to quoting always, to reduce accidental mistakes.

* - this is only a suggestion, not a limit. If you sent me code with [ ! "$x" ] or [[ $x ]] I will not blink twice. But if you sent [ $x ] smoke will come out of my ears.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • 1
    [... or worse](https://image.tmdb.org/t/p/original/qCCo807zQcj4kaSGn5H6LTqK2dh.jpg) – Enlico Feb 28 '22 at 16:49
  • Thanks for the discussion @KamilCuk. I deliberately put the word "arguably" in there because I forget what the tests are (e.g. sometimes I think `-z` is a test for zero file size) and so getting rid of flags is getting rid of something that I have to remember. Totally agree about your final `[ $x ]` comment! :-D – IpsRich Mar 01 '22 at 14:37