Test for non-zero length string in Bash: [ -n "$var" ] or [ "$var" ]

Viewed 184103

I've seen Bash scripts test for a non-zero length string in two different ways. Most scripts use the -n option:

#!/bin/bash
# With the -n option
if [ -n "$var" ]; then
  # Do something when var is non-zero length
fi

But the -n option isn't really needed:

# Without the -n option
if [ "$var" ]; then
  # Do something when var is non-zero length
fi

Which is the better way?

Similarly, which is the better way for testing for zero-length:

if [ -z "$var" ]; then
  # Do something when var is zero-length
fi

or

if [ ! "$var" ]; then
  # Do something when var is zero-length
fi
7 Answers

Unfortunately, I haven't been able to find out why there are two syntaxes for this in the first place. Both seem to have been introduced at the same time with Version 7 Unix in 1979.

The 1994 Single Unix Specification preferred the -n and -z syntax. The same recommendation has been copied verbatim into every version of POSIX since, including the latest version POSIX.1-2017:

The two commands:

test "$1"
test ! "$1"

could not be used reliably on some historical systems. Unexpected results would occur if such a string expression were used and $1 expanded to '!', '(', or a known unary primary. Better constructs are:

test -n "$1"
test -z "$1"

respectively.

I suppose that if you want to pedantically follow every recommendation in the specification then you should keep using -n and -z, but seriously, do you need compatibility with systems that are over 28 years old?

In my opinion, the readability of if [ "$var" ] and if [ ! "$var" ] makes that syntax the clear winner. But the bottom line is that there's no functional difference, so go with your personal preference.

Related