bash string comparison — equality, contains, starts with
Quick Answer
# Equal
[[ "$a" == "$b" ]] && echo "equal"
# Not equal
[[ "$a" != "$b" ]] && echo "different"
# Empty / not empty
[[ -z "$var" ]] && echo "empty"
[[ -n "$var" ]] && echo "not empty"
# Contains (glob pattern)
[[ "$str" == *"substr"* ]] && echo "contains"
Usage
String comparison in bash has many pitfalls. Use [[ ]] (not [ ]) for most cases.
Other causes & fixes
Regex match with =~
# Check if string matches a regex
if [[ "$email" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
echo "valid email"
fi
# Access capture groups via BASH_REMATCH
if [[ "2024-01-15" =~ ^([0-9]{4})-([0-9]{2})-([0-9]{2})$ ]]; then
echo "year=${BASH_REMATCH[1]}"
fi
Starts with / ends with
# Starts with "prefix"
[[ "$str" == prefix* ]] && echo "starts with prefix"
# Ends with ".log"
[[ "$str" == *.log ]] && echo "ends with .log"
Case-insensitive comparison
shopt -s nocasematch
[[ "Hello" == "hello" ]] && echo "match"
shopt -u nocasematch # restore
String length
str="hello"
echo ${#str} # 5
Related