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

String Comparison

In this page:

  1. String Comparison

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

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.