Bash How to Compare Numbers

Bash How to Compare Numbers

The first option is to use the command test to binary compare numbers. For example:

if [ $a -eq $b ]; then
echo "a == b"
else
echo a!=b
fi

An operator”-eq” is equal to, -gt is greater than. For more operators type:

man test

If you are more familiar with symbols “<, >, <=, >=, ==” use double parentheses:

if (( $a < $b )); then
echo "a < b"
fi

For POSIX shells that don’t support double parentheses use test command.

Few examples of test options:

  • -ge: greater or equal
  • -le: less or equal
  • -lt: less than
  • -ne: not equal

Leave a Comment