Check if String is Empty
To check if string is empty in Bash, we can make an equality check with the given string and empty string using string equal-to =
operator, or use -z
string operator to check if the size of given string operand is zero.
In this tutorial, we will go through examples using the above mentioned techniques to check if the given string is empty.
Examples
Check if String is Empty using Equal to Operator
In the following script, we check if string s
is empty using string equal to operator =
.
The expression [ "$s" = "" ]
returns true if s is empty or false if s
is not empty.
Example.sh
s=""
if [ "$s" = "" ];
then
echo "String is empty."
else
echo "String is not empty."
fi
Output
String is empty.
Now, let us assign s with a non empty string value, and run the program again.
Example.sh
s="hello world"
if [ "$s" = "" ];
then
echo "String is empty."
else
echo "String is not empty."
fi
Output
String is not empty.
Check if String is Empty using -z String Operator
-z string operator checks if given string operand’s size is zero. If the string operand is of zero length, then it returns true, or else it returns false.
The expression to check if string is empty is [ -z "$s" ]
where s
is string.
Example.sh
s=""
if [ -z "$s" ];
then
echo "String is empty."
else
echo "String is not empty."
fi
Output
String is empty.
Now, let us assign s with a non empty string value, and run the program again.
Example.sh
s="hello world"
if [ -z "$s" ];
then
echo "String is empty."
else
echo "String is not empty."
fi
Output
String is not empty.
Conclusion
In this Bash Tutorial, we have learnt how to check if string is empty in Bash Shell.