-1

Is there any difference between

if [ ! -z "$var" ] then
    # do smth
fi

and

if [ "$var" ] then
    # do smth
fi

They both seem to check if variable is set

zovube
  • 46
  • 7
  • -z string True if the string is null (an empty string) -- https://stackoverflow.com/questions/18096670/what-does-z-mean-in-bash – Book Of Zeus Sep 23 '21 at 00:11
  • 1
    @BookOfZeus That means that `! -z` is true if the string is *not* empty. Which is what `[ "$var" ]` also tests. – Barmar Sep 23 '21 at 00:13

2 Answers2

3

Yes, they're equivalent, but there are a couple of notes that apply to both of them:

  • You need either a semicolon or a line break between ] and the then keyword, or it'll misparse them weirdly.
  • They're not testing whether the variable is set, they're testing whether it's set to something other than the empty string (see this question for ways to check whether a variable is truly unset).

However, I actually prefer a third also-equivalent option:

if [ -n "$var" ]; then

I consider this semantically clearer, because the -n operator specifically checks for something being non-empty.

Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151
1

There's no difference between

[ ! -z "$var" ]
[ -n "$var" ]
[ "$var" ]

All of them are true if $var is not empty.

Barmar
  • 741,623
  • 53
  • 500
  • 612