DEV Community

Donald Feury
Donald Feury

Posted on • Originally published at donaldfeury.xyz on

15 2

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More