Check for Empty String in Bash

10 Mar 2014

A common task is to check if a string is empty in a programming language; with bash, you can do it easily, just be careful with its syntax and semantics.

-n or -z string comparison operators are created for such purpose; -n checks whether the string is not null (string), which returns false when it is an empty string. In addtion, the -n test requires that the string BE QUOTED within the test brackets. As a better scripting practice, ALWAYS quote a tested string:

if [ -n "$VAR" ]; then
    echo "VAR is not empty"

Similarly, -z operator checks whether the string is null - the opposite of -n:

if [ -z "$VAR" ]; then
    echo "VAR is empty"