Test variable existence with test -z
In this step, you will learn how to check if a variable is empty or not set using the test
command with the -z
option. This is useful in scripting to make decisions based on whether a variable has a value.
The test
command is used to evaluate conditional expressions. The -z
option checks if the length of a string is zero. If the string is empty (or the variable is not set), the test is true.
Let's test if a variable named MY_VARIABLE
is set. First, we'll make sure it's not set.
Type the following command and press Enter:
unset MY_VARIABLE
The unset
command removes a variable. Now, let's use test -z
to check if MY_VARIABLE
is empty. We'll combine it with echo
to see the result of the test. The &&
operator executes the second command only if the first command succeeds (returns a true value, which for test
means the condition is met).
Type the following command and press Enter:
test -z "$MY_VARIABLE" && echo "MY_VARIABLE is empty or not set"
Since we just unset MY_VARIABLE
, the test -z "$MY_VARIABLE"
condition is true (the variable is empty), so the echo
command will execute.
You should see the output:
MY_VARIABLE is empty or not set
Now, let's set a value for MY_VARIABLE
.
Type the following command and press Enter:
MY_VARIABLE="Hello"
Now, let's run the same test -z
command again.
Type the following command and press Enter:
test -z "$MY_VARIABLE" && echo "MY_VARIABLE is empty or not set"
This time, MY_VARIABLE
has the value "Hello", so it is not empty. The test -z "$MY_VARIABLE"
condition is false, and the echo
command will not execute.
You should see no output from the echo
command this time.
This demonstrates how test -z
can be used to check if a variable is empty or not set. This is a fundamental concept used in shell scripting for conditional logic.