I've seen bash scripts test for 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
The correct answer is the following:
Note the use of the
[[...]]
, which correctly handles quoting the variables for you.It is better to use the more powerful
[[
as far as Bash is concerned.Usual cases
The above two constructs look clean and readable. They should suffice in most cases.
Note that we don't need to quote the variable expansions inside
[[
as there is no danger of word splitting and globbing.Rare cases
In the rare case of us having to make a distinction between "being set to an empty string" vs "not being set at all", we could use these:
We can also use the
-v
test:Related posts and documentation
There are a plenty of posts related to this topic. Here are a few:
[[
vs[
[
vs[[
use
case/esac
to testAn alternative and perhaps more transparent way of evaluating an empty env variable is to use...
Edit: This is a more complete version that shows more differences between
[
(akatest
) and[[
.The following table shows that whether a variable is quoted or not, whether you use single or double brackets and whether the variable contains only a space are the things that affect whether using a test with or without
-n/-z
is suitable for checking a variable.If you want to know if a variable is non-zero length, do any of the following:
-n
and quote the variable in single brackets (column 4a)-n
(columns 1b - 4b)Notice in column 1a starting at the row labeled "two" that the result indicates that
[
is evaluating the contents of the variable as if they were part of the conditional expression (the result matches the assertion implied by the "T" or "F" in the description column). When[[
is used (column 1b), the variable content is seen as a string and not evaluated.The errors in columns 3a and 5a are caused by the fact that the variable value includes a space and the variable is unquoted. Again, as shown in columns 3b and 5b,
[[
evaluates the variable's contents as a string.If you're using
[
, the key to making sure that you don't get unexpected results is quoting the variable. Using[[
, it doesn't matter.The error messages, which are being suppressed, are "unary operator expected" or "binary operator expected".
This is the script that produced the table above.
Here are some more tests
True if string is not empty:
True if string is empty: