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
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
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