Skip to content
TrySitePrice

How To Bash Shell Find Out If a Variable Is Empty Or Not

Best/Tutorial

In bash shell, you can check if a variable is empty or not using the following syntax:

if [ -z "$VARIABLE_NAME" ]; then

 echo "Variable is empty"

else

 echo "Variable is not empty"

fi

The -z operator checks if the length of the string stored in the $VARIABLE_NAME is zero, indicating that the variable is empty. If the length is non-zero, the if statement will evaluate to false and the code inside the else block will be executed.

You can also check if a variable is not empty using the following syntax:

if [ -n "$VARIABLE_NAME" ]; then

 echo "Variable is not empty"

else

 echo "Variable is empty"

fi

The -n operator checks if the length of the string stored in the $VARIABLE_NAME is non-zero, indicating that the variable is not empty. If the length is zero, the if statement will evaluate to false and the code inside the else block will be executed.