Home > Enterprise >  Difference between `if [ ! -z "$var" ] then` and `if [ "$var"] then" in bas
Difference between `if [ ! -z "$var" ] then` and `if [ "$var"] then" in bas

Time:09-23

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

CodePudding user response:

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.

CodePudding user response:

There's no difference between

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

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

  •  Tags:  
  • bash
  • Related