How to Compare Numbers in Bash: Syntax and Examples
In bash, you compare numbers using the
if statement combined with test expressions like -eq (equal), -ne (not equal), -lt (less than), -le (less or equal), -gt (greater than), and -ge (greater or equal). Use these inside square brackets [ ] or double square brackets [[ ]] for numeric comparisons.Syntax
Use if with test expressions inside square brackets to compare numbers. The common operators are:
-eq: equal-ne: not equal-lt: less than-le: less than or equal-gt: greater than-ge: greater than or equal
Example syntax:
if [ number1 -operator number2 ]; then
# commands
fibash
if [ number1 -eq number2 ]; then echo "Numbers are equal" fi
Example
This example compares two numbers and prints which one is greater or if they are equal.
bash
#!/bin/bash num1=10 num2=20 if [ $num1 -eq $num2 ]; then echo "$num1 is equal to $num2" elif [ $num1 -lt $num2 ]; then echo "$num1 is less than $num2" else echo "$num1 is greater than $num2" fi
Output
10 is less than 20
Common Pitfalls
Common mistakes include:
- Using
==inside single square brackets for numbers (it works for strings, not numbers). - Not adding spaces around brackets and operators.
- Forgetting to use
$before variable names.
Correct numeric comparison requires -eq, -lt, etc., inside [ ] with spaces.
bash
# Wrong way: num1=5 num2=10 if [ $num1 == $num2 ]; then echo "Equal" fi # Right way: if [ $num1 -eq $num2 ]; then echo "Equal" fi
Quick Reference
| Operator | Meaning |
|---|---|
| -eq | Equal to |
| -ne | Not equal to |
| -lt | Less than |
| -le | Less than or equal to |
| -gt | Greater than |
| -ge | Greater than or equal to |
Key Takeaways
Use -eq, -ne, -lt, -le, -gt, and -ge inside [ ] for numeric comparisons in bash.
Always put spaces around brackets and operators in test expressions.
Use $ before variable names to get their values in comparisons.
Avoid using == for numbers; it is for string comparison in single brackets.
Double square brackets [[ ]] support more features but -eq style operators remain standard for numbers.