Test string emptiness with test -z
In this step, you will learn how to check if a string is empty in Linux using the test
command with the -z
option. This is a fundamental operation when working with strings in shell scripting.
The test
command is used to evaluate conditional expressions. The -z
option specifically checks if the length of a string is zero. If the string is empty, the test is true; otherwise, it is false.
Let's try it out in the terminal. First, we'll define an empty string variable. In shell scripting, you define a variable by typing its name, followed by an equals sign (=
), and then the value. There should be no spaces around the equals sign.
Type the following command to define an empty string variable named my_string
:
my_string=""
Now, let's use the test -z
command to check if my_string
is empty. The test
command itself doesn't produce output; its result is used to control the flow of a script (which you'll learn later). However, we can see its result by checking the exit status of the previous command using echo $?
. An exit status of 0
indicates success (true), and a non-zero status indicates failure (false).
Type the following command to test if my_string
is empty:
test -z "$my_string"
After running the test
command, check its exit status:
echo $?
Since my_string
is empty, the test -z
command should evaluate to true, and the echo $?
command should output 0
.
Now, let's define a non-empty string:
another_string="Hello"
And test if it's empty:
test -z "$another_string"
Check the exit status:
echo $?
This time, since another_string
is not empty, the test -z
command should evaluate to false, and the echo $?
command should output 1
.
Understanding how to test for empty strings is crucial for writing robust shell scripts that handle different inputs correctly.