Syntax:
‘-v’ or ‘-z’ option is used to check the variable is set or unset. The above Boolean expression will return true if the variable is set and returns false if the variable is not set or empty.
Parameter substitute is another way to check the variable is set or unset. If the variable is set, then the value of the string will return otherwise null will return.
Example-1: Check the variable is set or unset using ‘-z’ option
Create a bash file named check_var1.sh with the following script. Here, the first `if` condition will return true and “Num variable is not set” will print. In the next statement, 20 is assigned to the variable, $Num. The second `if` condition will returns false and “Num is set and the value of Num=20” will print.
check_var1.sh
#Check the variable is set or not
if [ -z ${Num} ]; then
echo "‘Num’ variable is not set"
else
echo "‘Num’ variable is set"
fi
#Assign a value
Num=20
#Check the variable is set or not after assigning the value
if [ -z ${Num} ]; then
echo "’Num’ variable is not set"
else
echo "’Num is set and the value of Num=$Num"
fi
Run the script.
Example-2: Check the variable is set or unset using parameter substitute
Create a bash file named “check_var2.sh” and add the following script. Here, a string value is assigned to the variable, $str before checking the variable is set or unset. The ‘if’ condition will return true and the message, “’str’ variable is set and the value is Hello” will print.
check_var2.sh
#Set the variable
str=”Hello”
#Assign the value “World” to checkval if the str variable is set
checkval=${str+”World”}
#Check the variable is set or unset
if [ $checkval -eq “World” ]; then
echo "‘str’ variable is set and the value is $str"
else
echo "‘str’ variable is not set"
fi
Run the script.
Example-3: Check the variable is empty or not
Create a bash file named “check_var3.sh” and add the following script. The script will store the first command-line argument into a variable, $argv that is tested in the next statement. The output will be “First argument is empty” if no argument is passed otherwise the value of the first argument will be printed.
check_var3.sh
#Read the first command-line argument value
argv="$1"
#Check the first argument value is provided or not
[ -v "$argv" ] && echo "First argument is empty" ||
echo "The value of the first argument is $argv"
Run the script without any argument.
Run the script with an argument.
Conclusion
Different ways to check the variable is set or unset or empty are shown in this tutorial by using various examples. Hope, this tutorial will help the users to learn the ways of testing any bash variable.