← Back to Bash Course | Chapter 5: Functions | Lesson 8 of 11

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:

  1. String Comparison
Syntax
bash
[[ "$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

bash
#!/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
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
  1. Using = or == inside [ ] with unquoted variables, which breaks when the value is empty or has spaces.
  2. Using -eq for strings instead of =.
  3. Forgetting the spaces around =, as in [ "$a"="$b" ], which is always true.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.