DEV Community 👩‍💻👨‍💻

Donald Feury
Donald Feury

Posted on • Originally published at donaldfeury.xyz on

How to check if a string is empty in Bash

How to check if a string is empty in Bash

To check if a string is empty in a Bash script, use the -z conditional which returns 0 (true) if the length of the string is 0 and 1 (false) if it is greater than 0.

myVar="hello"

if [[-z "$myVar"]]; then
    echo "myVar is empty"
else
    echo "myVar is not empty"
fi

Enter fullscreen mode Exit fullscreen mode

Alternatively, you can check if a bash string is NOT empty using -n and take the opposite using !.

myVar=""

if [[! -n "$myVar"]]; then
    echo "myVar is empty"
else
    echo "myVar is not empty"
fi

Enter fullscreen mode Exit fullscreen mode

Related


Did you find this information useful? If so, consider heading over to my donation page and drop me some support.

Want to ask a question or just chat? Contact me here

Top comments (0)

Let's Get Wacky


Use any Linode offering to create something unique or silly in the DEV x Linode Hackathon 2022 and win the Wacky Wildcard category

Join the Hackathon <-