Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to determine if a bash variable is empty?

What is the best way to determine if a variable in bash is empty ("")?

I have heard that it is recommended that I do if [ "x$variable" = "x" ]

Is that the correct way? (there must be something more straightforward)
by

2 Answers

akshay1995
This will return true if a variable is unset or set to the empty string ("").

if [ -z "${VAR}" ];
sandhya6gczb
In Bash, when you're not concerned with portability to shells that don't support it, you should always use the double-bracket syntax:

Any of the following:

if [[ -z $variable ]]
if [[ -z "$variable" ]]
if [[ ! $variable ]]
if [[ ! "$variable" ]]

In Bash, using double square brackets, the quotes aren't necessary. You can simplify the test for a variable that does contain a value to:

if [[ $variable ]]

This syntax is compatible with ksh (at least ksh93, anyway). It does not work in pure POSIX or older Bourne shells such as sh or dash.

Login / Signup to Answer the Question.