How to Check If a Variable is Empty/Null in Bash? [4 Methods]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

To check if a variable is empty or null in Bash, use -z, -n, equal comparison with if statement. In this article, I will demonstrate 4 methods to check if a variable is empty/null or not in Bash utilizing different conditional operators.

What is an Empty/Null Variable in Bash?

An empty variable is a variable that has been declared but contains no value or has a value that. This means that the variable has been assigned, but it holds a null value. In a word, if a variable contains no value in it, then it’s called an empty or null variable. Typically, an empty variable appears for two reasons:

  1. The variable was not initialized.
  2. The variable was assigned a value at some point, but the value was later cleared.

4 Ways to Check If a Variable is Empty or Not in Bash

Bash provides several conditional tasks to check whether a variable is empty or not, including variable length check, parameter expansion check, double square bracket check, equal operator check, negation operator check, etc. Let’s explore them.

1. Using ‘-z’ Option

The “-z” option in ‘if’ statement checks if a string contains zero length, i.e. determines if the assigned variable is empty. If the specified variable length is zero, a True expression is executed.

To check if a variable is empty or null, use the -z option with the test command either in the format if [ -z "$variable" ] or if test -z "$variable". Let’s take a look at the following example using the later one:

#!/bin/bash

#Defining an empty string variable
xyz=""

#Checking if variable is empty
if test -z "$xyz"; then
    echo "The variable is empty."
fi
EXPLANATION

In the script, the ‘if’ conditional checks whether the defined variable ‘xyz’ is empty. If the variable is empty, it echoes “The variable is empty.” employing the echo command.

Using '-z' option with 'test' command for empty variable validationAs you can see from the figure above, the variable ‘xyz’ contains a string with zero (0) length. This means that the ‘xyz’ variable is empty.

Whenever using if statement with [ ], remember to add spaces between the brackets and text inside it.

2. Using “-n” Option

In the ‘if’ statement, the -n option evaluates whether a variable has a value with non-zero length i.e. the variable is not empty. If the variable contains any value, then the test returns true. However, you can use the -n parameter to check whether a variable that contains a number is not empty. In this case, Bash treats numbers as strings.

For instance, you can do the following non-empty variable testing using the if [ -n "$number" ] syntax like the below script:

#!/bin/bash

#Defining a variable
number=41

#Checking if variable is not empty using “-n” option
if [ -n "$number" ]; then
    echo "The variable is not empty."
fi
EXPLANATION

Here, the -n option checks if the defined variable ‘number’ has a value. Since the variable has value 41, the condition evaluates to true and the script prints “The variable is not empty.”

Using '-n' option with '[ ]' construct for non-empty variable validationIn the figure above, you can see that the variable ‘number’ has a string value of ‘41’. Therefore, the string length of the variable is non-zero. This indicates that the variable ‘number’ is not empty.

3. Using Parameter Expansion

Parameter expansion is a strong feature in Bash that is used for a brief validation of variables i.e. whether it is empty or not. The syntax for parameter expansion practiced in empty variable validation is ${variable-}.

To find out if a variable is empty or not, use the if [ -z "${variable-}" ] & if [ -n "${variable-}" ] syntaxes to execute the output when it becomes true. For example:

#!/bin/bash

#Defining an empty string variable
xyz=""
abc='Hello, Linux!'

#Using parameter expansion to check if the variable is empty
if [ -z "${xyz-}" ]; then
    echo "The variable is empty."
fi
#Using parameter expansion to check if the variable is not empty
if [ -n "${abc-}" ]; then
    echo "The variable is not empty."
fi
EXPLANATION

Since two variables are set such as one as an empty string and another with some value in this case, the parameter expansions ${xyz-} and ${abc-} evaluate to $xyz and $abc and the script prints “The variable is empty.” and “The variable is not empty.” respectively resulting from the conditional check.

Using parameter expansion for empty & non-empty variable validationIn the above snapshot, the variable ‘xyz’ has a string length of zero (0), which is an empty variable, whereas the variable ‘abc’ holds the value ‘Hello, Linux!’, which is a non-empty variable.

4. Using Equal Operator

The “==” operator is generally used for string comparison, pattern matching, etc. However, this operator can be used within single square brackets “[ ]” to check if a variable is empty by comparing it with an empty string.

Here’s an example of how you can use if [ "$variable" = "" ] syntax to check if a variable is empty:

#!/bin/bash

#Defining an empty variable
xyz=""
if [ "$xyz" == "" ]; then
    echo "The variable is empty."
fi
EXPLANATION

In the above code, the condition inside the “[ ]” operator checks if the specified variable ‘xyz’ is equal to an empty string. If the variable is empty, then the condition becomes true and the script displays “The variable is empty.”

Using '=' operator for empty variable validationWhen the variable ‘xyz’ is found as an empty string in ‘if’, it is treated as an empty variable as shown in the figure above.

How to Check if a Variable is Not Empty in Bash?

The “!” operator in Bash is used to reverse the output of a condition. This operator along with the equal “=” operator can be used within single square brackets “[ ]” for empty variable validation.

To check if a variable is empty or not, use if [ "$variable" != "" ] syntax in the following manner:

#!/bin/bash

#Defining a variable
name="N"

#Checking if variable is not empty using “!=” operator
if [ "$name" != "" ]; then
    echo "The variable is not empty."
fi
EXPLANATION

The ‘if’ condition here compares the specified ‘name’ variable with an empty string and checks if the variable is not equal to the empty string. As the variable contains a value, the condition becomes true and the script shows “The variable is not empty.”

Using '!' operator with '=' for non-empty variable validationFrom the above figure, you can see that the variable ‘name’ is treated as a non-empty variable when the value N is specified in ‘if’.

Conclusion

In summary, this article provides you with several options to check whether a variable is empty or not in Bash. You can choose any method according to your preference and use this as a best practice for writing flexible Bash scripts.

People Also Ask

How can I check if a bash variable is null?

To check if a Bash variable is null/empty, use -z option with if statement. Here’s how:

if [ -z "$variable" ]; then
  echo "Variable is empty."
else
  echo "Variable is not empty."
fi

This script will determine whether $variable is null/empty or not.

Why check variable emptiness in Bash?

Checking variable emptiness in Bash is crucial for several reasons:

  1. To ensure proper handling and validation of user input.
  2. To prevent unintended errors.
  3. To maintain data integrity.
  4. To control the conditional decisions.

What’s the difference between checking if a variable is unset and checking if it’s empty?

Checking if a variable is unset confirms whether the variable has been defined or assigned any value. The ‘-v’ operator checks if a variable is set using the syntax if [ -v variable ]. On the contrary, checking if a variable is empty ensures that the variable contains an empty string. The ‘-z’ operator validates this check using the if [ -z "$variable" ].

What happens when a variable is kept empty in Bash?

When a variable is empty in Bash, it means that the variable has no value assigned to it. In such cases, the variable is considered to be null or empty. So, keeping a variable empty may lead to unwanted crash of a program. Also, it leads to unnecessary wastage of memory.

Can I use a single ‘if’ statement to check for both empty and non-empty variables?

Yes, to check for both empty and non-empty variables within the same ‘if‘ statement, you can use the -z and -n options. For instance:

#!/bin/bash

#Defining a variable
variable=""

#Checking for empty & non-empty variables
if [ -z "$variable" ]; then
    echo "The variable is empty."
elif [ -n "$variable" ]; then
    echo "The variable is not empty."
fi

Related Articles


<< Go Back to If Statement in Bash | Bash Conditional Statements | Bash Scripting Tutorial

Rate this post
Nadiba Rahman

Hello, This is Nadiba Rahman, currently working as a Linux Content Developer Executive at SOFTEKO. I have completed my graduation with a bachelor’s degree in Electronics & Telecommunication Engineering from Rajshahi University of Engineering & Technology (RUET).I am quite passionate about crafting. I really adore exploring and learning new things which always helps me to think transparently. And this curiosity led me to pursue knowledge about Linux. My goal is to portray Linux-based practical problems and share them with you. Read Full Bio

Leave a Comment