How to Compare Strings in Bash: Syntax and Examples
In bash, you compare strings using the
[ ] or [[ ]] test commands with operators like == or !=. For example, [ "$str1" = "$str2" ] returns true if the strings are equal.Syntax
Use [ ] or [[ ]] to compare strings in bash. Inside these brackets, use = or == to check if strings are equal and != to check if they are different. Always quote your variables to avoid errors with spaces or empty strings.
[ "$str1" = "$str2" ]: True if strings are equal.[ "$str1" != "$str2" ]: True if strings are not equal.[[ $str1 == $str2 ]]: Similar but more flexible and safer for pattern matching.
bash
[ "$str1" = "$str2" ] [[ $str1 == $str2 ]]
Example
This example shows how to compare two strings and print a message based on whether they match or not.
bash
#!/bin/bash str1="hello" str2="world" if [ "$str1" = "$str2" ]; then echo "Strings are equal" else echo "Strings are not equal" fi # Using [[ ]] with pattern matching pattern="hel*" if [[ $str1 == $pattern ]]; then echo "str1 matches the pattern" fi
Output
Strings are not equal
str1 matches the pattern
Common Pitfalls
Common mistakes include not quoting variables, which can cause errors if strings have spaces or are empty. Also, [ ] does not support pattern matching like [[ ]]. Avoid using single = inside [ ] for equality; use = or == instead.
bash
# Wrong: no quotes, can cause errors str1=hello world if [ "$str1" = "hello world" ]; then echo "Match" fi # Right: quotes prevent errors str1="hello world" if [ "$str1" = "hello world" ]; then echo "Match" fi
Output
Match
Quick Reference
| Operator | Meaning | Example |
|---|---|---|
| = | Equals | [ "$a" = "$b" ] |
| == | Equals (in [[ ]]) | [[ $a == $b ]] |
| != | Not equals | [ "$a" != "$b" ] |
| < | Less than (lexicographically) | [[ $a < $b ]] |
| > | Greater than (lexicographically) | [[ $a > $b ]] |
Key Takeaways
Always quote string variables when comparing to avoid errors.
Use [[ ]] for safer and more flexible string comparisons.
Use = or == for equality and != for inequality in string tests.
Avoid unquoted variables inside [ ] for string comparison.
Pattern matching works only with [[ ]] and not with [ ].