0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Check if a Variable is Empty in Bash

In Bash, you can check if a variable is empty by using if [ -z "$variable" ]. This condition returns true if the variable has no value or is unset.
📐

Syntax

The basic syntax to check if a variable is empty in Bash uses the -z test inside an if statement.

  • -z: Tests if the string length is zero (empty).
  • "$variable": The variable to check, quoted to avoid errors if empty or unset.
  • if [ condition ]; then ... fi: Standard Bash conditional syntax.
bash
if [ -z "$variable" ]; then
  echo "Variable is empty"
else
  echo "Variable is not empty"
fi
💻

Example

This example shows how to check if a variable is empty and prints a message accordingly.

bash
#!/bin/bash

variable=""

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

variable="Hello"

if [ -z "$variable" ]; then
  echo "Variable is empty"
else
  echo "Variable is not empty"
fi
Output
Variable is empty Variable is not empty
⚠️

Common Pitfalls

Common mistakes when checking if a variable is empty include:

  • Not quoting the variable, which can cause errors if the variable is unset or contains spaces.
  • Using -n incorrectly; -n checks if a variable is not empty.
  • Confusing empty with unset variables; -z treats both as empty.
bash
# Wrong: Missing quotes can cause errors
if [ -z $variable ]; then
  echo "Empty"
fi

# Correct: Always quote variables
if [ -z "$variable" ]; then
  echo "Empty"
fi
📊

Quick Reference

TestMeaningExample
-z "$var"True if variable is empty or unsetif [ -z "$var" ]; then ... fi
-n "$var"True if variable is not emptyif [ -n "$var" ]; then ... fi
"$var" = ""True if variable equals empty stringif [ "$var" = "" ]; then ... fi

Key Takeaways

Use if [ -z "$variable" ] to check if a variable is empty or unset in Bash.
Always quote variables in tests to avoid errors with empty or unset values.
The -z test returns true when the variable is empty; -n returns true when not empty.
Empty and unset variables are treated the same by the -z test.
Avoid missing quotes and confusing -z with -n to prevent bugs.