bash how to compare numbers

Answer

First option is use 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 which 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

Was this information helpful to you? You have the power to keep it alive.
Each donated € will be spent on running and expanding this page about UNIX Shell.