When working with Bash scripts, handling strings efficiently is a crucial component of making scripts useful and reliable. String comparison in Bash is particularly important for conditionals, pattern matching, and flow control. Mastering these comparisons helps automate tasks, validate data, and make decisions dynamically based on user input or file contents.
TL;DR
Bash string comparison allows developers to compare strings for equality, inequality, pattern matching, and sorting. It uses a variety of operators such as ==, !=, <, and > within test brackets or double square brackets. Paying attention to quoting and testing syntax is essential to avoid bugs. This guide covers every aspect of Bash string comparison with examples to help you confidently apply it in your scripts.
Understanding String Comparison in Bash
In Bash, strings are compared using conditional expressions. These expressions fall into two categories:
- Equality and inequality checks
- Lexicographical (alphabetical) comparisons
You can perform these comparisons inside one of two conditional notations:
[ expression ]– older, more POSIX-compliant syntax[[ expression ]]– Bash-specific and more flexible
1. String Equality Check
Use the == operator to check if two strings are equal.
#!/bin/bash
str1="hello"
str2="world"
if [ "$str1" == "$str2" ]; then
echo "Strings match"
else
echo "Strings do not match"
fi
Note: When using [ ], it’s safer to wrap variables in quotes to avoid errors from uninitialized or multi-word strings.
2. String Inequality
Use the != operator to test if strings are not equal.
if [[ "$str1" != "$str2" ]]; then
echo "Different strings"
fi
3. Checking for Empty Strings
There are specific ways to see if a string is empty or non-empty.
-z "$var": True if the string is zero length.-n "$var": True if the string is non-zero length.
var=""
if [ -z "$var" ]; then
echo "The string is empty"
fi
4. Lexicographical Comparisons
Bash can also compare strings alphabetically. Use these operators:
<: True if left string comes before right string>: True if left string comes after right string
Important: These operators work only with [[ ]]; using them with single brackets can lead to unexpected behavior or syntax errors.
str1="apple"
str2="banana"
if [[ "$str1" < "$str2" ]]; then
echo "$str1 comes before $str2"
fi
The Importance of Quoting Strings
One of the most common errors in Bash string operations is forgetting to quote variables. For instance:
if [ $str1 == $str2 ]; then # Not safe!
If any of the variables are empty or contain spaces, this could throw an error. Instead, always quote them:
if [ "$str1" == "$str2" ]; then
Similarly, when checking for an empty string, -z $var is unsafe—use -z "$var" instead.
Using Wildcards in String Comparison
Wildcards can be useful when checking for pattern matches. This is possible in [[ ]] but not [ ].
filename="report_2024.txt"
if [[ "$filename" == report_*.txt ]]; then
echo "Pattern match found"
fi
This lets one search for strings that start, end, or contain specific patterns—ideal for filenames, input validation, and automation.
Case Sensitivity in Comparisons
Bash string comparison is case-sensitive by default. For example:
str1="Hello"
str2="hello"
if [[ "$str1" == "$str2" ]]; then
echo "Match"
else
echo "Not a match"
fi
This will print Not a match. To perform a case-insensitive comparison, convert both strings to the same case using Bash parameter expansion:
str1="HELLO"
str2="hello"
if [[ "${str1,,}" == "${str2,,}" ]]; then
echo "Match"
fi
Here, ${str1,,} converts the string to lowercase.
Combining Multiple Conditions
Bash lets you evaluate several conditions at once using logical AND (&&) and logical OR (||):
if [[ "$user" == "admin" || "$user" == "root" ]]; then
echo "Privileged user"
fi
if [[ -n "$message" && "$status" == "success" ]]; then
echo "Success with message: $message"
fi
Best Practices for Bash String Comparison
- Always quote variables to prevent syntax errors and word splitting.
- Use
[[ ]]instead of[ ]when possible for extra safety and functionality. - Prefer lowercase variables when performing case-insensitive comparisons.
- Thoroughly test edge cases like empty strings, null values, and special characters.
Common Pitfalls to Avoid
- Using
<or>with[ ]causes errors—only use with[[ ]] - Forgetting to quote strings, resulting in unexpected behavior when variables are empty
- Confusing string comparison with numeric comparison operators—use proper syntax for each
Real-World Use Cases
Bash string comparisons are key in:
- User input validation – ensure responses match expected keywords
- Log file filtering – extract lines based on pattern match
- File verification – check if filenames follow a format
- Automated deployment scripts – branch logic based on string status or version tags
FAQ
- Can I use string comparison with
ifin one line? - Yes, write it like this:
if [[ "$a" == "$b" ]]; then echo "Match"; fi - What’s the difference between
[[ ]]and[ ]? [[ ]]is a Bash keyword that supports pattern matching and doesn’t require quoting around variables, making it more robust.[ ]is POSIX-compliant but more limited.- What if I forget to quote my strings?
- Unquoted variables can result in syntax errors or unexpected behavior, especially when values are empty or have spaces. Always quote your strings in comparisons.
- Are comparisons case-sensitive?
- Yes, string comparisons in Bash are case-sensitive by default. Use parameter expansion (like
${var,,}) for case-insensitive matching. - How do I compare part of a string?</

