← Back to Bash Course | Chapter 4: Loops | Lesson 9 of 14

Comparison Operators

Comparison operators are like a balance scale that checks whether one number is bigger, smaller or the same as another. Bash has one set of scale words for square brackets and another set for double parentheses.

In this page:

  1. Comparison Operators
Syntax
bash
[[ $a -eq $b ]]   # also -ne -lt -le -gt -ge
(( a == b ))      # also != < <= > >=

Comparison Operators

Inside [[ ]] or (( )), numeric comparisons use -eq -ne -lt -le -gt -ge (in [[ ]]) or the familiar == != < <= > >= (in (( ))).

Bash keeps numeric comparison syntax separate from string comparison to avoid ambiguity. Mixing up -eq (numeric) with == in the wrong context is a common beginner mistake.

Warning: Using == inside [ ] (single brackets) works for strings, but for numbers you must use -eq, not ==.

Example: Comparison Operators

bash
#!/bin/bash
a=5
b=8

if [ "$a" -lt "$b" ]; then
    echo "$a is less than $b"
fi

if (( a < b )); then
    echo "Using (( )): $a is less than $b"
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 > and < inside [ ] for numbers, which are treated as redirections; use -gt and -lt.
  2. Using -eq on strings, which gives integer expression expected.
  3. Forgetting spaces inside brackets, as in [$a -eq 1].

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.