String Comparison
String comparison is like checking whether two name tags spell the same name. Bash can also test if a word fits a pattern, like 'starts with A'.
In this page:
Syntax
[[ "$string1" == "$string2" ]]
[[ "$string1" != "$string2" ]]
[[ "$string1" < "$string2" ]]
String Comparison
Inside [[ ]], strings are compared with == (equal), != (not equal), and lexicographically with </>. [[ ]] also supports pattern matching with == against a glob pattern on the right side.
String comparison is distinct from the numeric -eq/-lt operators covered earlier.
Warning:
Comparing strings with numeric operators like
-eq gives wrong or error results — always use ==/!= for strings.Example: String Comparison
#!/bin/bash
a="apple"
b="banana"
if [[ "$a" == "$b" ]]; then
echo "Equal"
else
echo "Not equal"
fi
if [[ "$a" == a* ]]; then
echo "$a starts with 'a'"
fi
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
=or==inside[ ]with unquoted variables, which breaks when the value is empty or has spaces. - Using
-eqfor strings instead of=. - Forgetting the spaces around
=, as in[ "$a"="$b" ], which is always true.
🔒
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: