Home » Linux » Shell » How to Check if a String is Empty in Bash Scripts

How to Check if a String is Empty in Bash Scripts

This short article will demonstrate how to check whether a string variable is empty in Bash and other Shell scripts in Linux, with examples.

Bash Operators

Bash operators are the symbols and expressions that perform comparisons, assignments, and arithmetic.

The -z Bash Operator

The -z operator returns true if a string variable is null or empty.

How the use the -z Bash Operator

After declaring a string variable, use the -z operator in an if statement to check whether a string is empty or not:

MY_STRING=""

if [ -z $MYSTRING ]
then
    echo "String is empty"
else
    echo "String is not empty"
fi

For more Shell scripting tips, check out or Bash/Shell scripting articles!

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment