In Bash scripting, it is common to check whether a variable has a value or not. In this article, we will discuss how to check if a variable is empty or not using different methods.
Method 1: Using if statement
The easiest way to check if a variable is empty is by using an if statement. Here is a sample code:
#!/bin/bash
my_var=""
if [ -z "$my_var" ]; then
echo "Variable is empty"
else
echo "Variable is not empty"
fi
In the above example, we check if the variable my_var
is empty using the -z
option, which returns true if the length of the string is zero. If the variable is empty, the script will print “Variable is empty”, otherwise, it will print “Variable is not empty”.
Method 2: Using null coalescing operator
In Bash 4.2 and later versions, you can use the null coalescing operator :-
to check if a variable is empty. Here is a sample code:
#!/bin/bash
my_var=""
echo ${my_var:-"Variable is empty"}
In the above example, we use the null coalescing operator to check if the variable my_var
is empty. If the variable is empty, the script will print “Variable is empty”, otherwise, it will print the value of my_var
.
Method 3: Using parameter expansion
In Bash, you can also use parameter expansion to check if a variable is empty. Here is a sample code:
#!/bin/bash
my_var=""
echo ${my_var:+"Variable is not empty"}
In the above example, we use the parameter expansion to check if the variable my_var
is not empty. If the variable is not empty, the script will print “Variable is not empty”, otherwise, it will print nothing.
Related concepts
Checking for null variables
In Bash, you can also check if a variable is null or not. Here is a sample code:
#!/bin/bash
my_var=""
if [ -n "$my_var" ]; then
echo "Variable is not null"
else
echo "Variable is null"
fi
In the above example, we check if the variable my_var
is null using the -n
option, which returns true if the length of the string is non-zero. If the variable is null, the script will print “Variable is null”, otherwise, it will print “Variable is not null”.
Checking for unset variables
In Bash, you can also check if a variable is unset or not. Here is a sample code:
#!/bin/bash
if [ -z ${my_var+x} ]; then
echo "Variable is unset"
else
echo "Variable is set"
fi
In the above example, we check if the variable my_var
is unset using the ${my_var+x}
syntax, which returns true if the variable is unset. If the variable is unset, the script will print “Variable is unset”, otherwise, it will print “Variable is set”.
Conclusion
In conclusion, checking if a variable is empty is a common task in Bash scripting. In this article, we discussed three different methods to check if a variable is empty using if statements, null coalescing operator, and parameter expansion. We also discussed related concepts such as checking for null and unset variables. By mastering these concepts, you will be able to write more efficient and reliable Bash scripts.