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:
Syntax
[[ $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
#!/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
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
>and<inside[ ]for numbers, which are treated as redirections; use-gtand-lt. - Using
-eqon strings, which givesinteger expression expected. - Forgetting spaces inside brackets, as in
[$a -eq 1].
🔒
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: