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

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

6 Answers
6

Leave a Comment