Skip to main content

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

MethodBest ForOperatorReadability
-z operatorEmpty check-z "$var"Very clear
-n operatorNot empty check-n "$var"Very clear
Direct comparisonLegacy scripts"$var" = ""Clear
[[ ]] syntaxModern Bash[[ -z "$var" ]]Clear
Implicit booleanSimple 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

Use -z for clarity:

if [ -z "$string" ]; then
  echo "Empty"
fi

For Bash 4+, using [[ ]]:

if [[ -z $string ]]; then
  echo "Empty"
fi