In Bash shell, you can use the -z
operator to check if a variable has a NULL value or not. The -z
operator returns true if the length of the string stored in the variable is zero, which indicates a NULL value. Here’s an example of how you can use the -z
operator to check if a variable has a NULL value:
if [ -z "$var" ]; then
echo "var has a NULL value"
else
echo "var has a value of $var"
fi
Alternatively, you can use the -v
operator to check if the variable is set or not.
if [ -v var ]; then
echo "var has a value of $var"
else
echo "var is unset"
fi
In addition, you can also use the ${var+x}
notation to check if the variable is set or not. If the variable is set, it will return the variable value, otherwise, it will return the string x.
if [ "${var+x}" = "x" ]; then
echo "var is unset"
else
echo "var has a value of $var"
fi
It’s important to note that these commands only check whether the variable is set or unset and not if the variable contains a specific value.