How can I compare numbers in Bash?
In Bash, you should do your check in an arithmetic context:
if (( a > b )); then ...fi
For POSIX shells that don't support (())
, you can use -lt
and -gt
.
if [ "$a" -gt "$b" ]; then ...fi
You can get a full list of comparison operators with help test
or man test
.
Like this:
#!/bin/basha=2462620b=2462620if [ "$a" -eq "$b" ]; then echo "They're equal";fi
Integers can be compared with these operators:
-eq # Equal-ne # Not equal-lt # Less than-le # Less than or equal-gt # Greater than-ge # Greater than or equal
See this cheatsheet.