How to Check if String is Empty in Bash
• 1 min read
bash string check conditional validation
Quick Answer: Check if String is Empty in Bash
To check if a string is empty in Bash, use the -z operator: if [ -z "$text" ]; then. This returns true if the string is empty. For the opposite check (string is NOT empty), use -n.
Quick Comparison: Empty String Testing Methods
| Method | Best For | Operator | Readability |
|---|---|---|---|
| -z operator | Empty check | -z "$var" | Very clear |
| -n operator | Not empty check | -n "$var" | Very clear |
| Direct comparison | Legacy scripts | "$var" = "" | Clear |
| [[ ]] syntax | Modern Bash | [[ -z "$var" ]] | Clear |
| Implicit boolean | Simple checks | [ $var ] | Simple |
Bottom line: Use -z to check if empty, use -n to check if not empty.
Method 1: Using -z Operator
text=""
if [ -z "$text" ]; then
echo "String is empty"
fi
Method 2: Using -n Operator
text="Hello"
if [ -n "$text" ]; then
echo "String is not empty"
fi
Method 3: Direct Comparison
text=""
if [ "$text" = "" ]; then
echo "String is empty"
fi
Method 4: Using [[ ]]
text=""
if [[ -z $text ]]; then
echo "String is empty"
fi
# Or without -z
if [[ ! $text ]]; then
echo "String is empty"
fi
Check if Variable is Unset vs Empty
# Unset variable
if [ -z "${var+x}" ]; then
echo "Variable is unset"
fi
# Variable is empty but set
if [ -z "$var" ] && [ "${var+x}" ]; then
echo "Variable is set but empty"
fi
Practical Example
#!/bin/bash
username="$1"
# Check if argument provided
if [ -z "$username" ]; then
echo "ERROR: Username required"
echo "Usage: $0 <username>"
exit 1
fi
echo "Hello, $username"
Common Use Cases
Validate Input
read -p "Enter name: " name
if [ -z "$name" ]; then
echo "Name cannot be empty"
exit 1
fi
Default Value
name="${1:-anonymous}"
echo "Hello, $name"
Skip Empty Lines
while read -r line; do
[ -z "$line" ] && continue
echo "Processing: $line"
done < file.txt
Recommended Method
Use -z for clarity:
if [ -z "$string" ]; then
echo "Empty"
fi
For Bash 4+, using [[ ]]:
if [[ -z $string ]]; then
echo "Empty"
fi