Bash Numeric Comparison

Bash test command enables you to compare two numeric values. You can perform six different operations under numeric comparison which are listed in the below table-

Condition Explanation
[ num1 -gt num2 ] Checks if num1 is greater than num2.
[ num1 -ge num2 ] Checks if num1 is greater than or equal to num2.
[ num1 -lt num2 ] Checks if num1 is less than num2.
[ num1 -le num2 ] Checks if num1 is less than or equal to num2.
[ num1 -eq num2 ] Checks if num1 is equal to num1.
[ num1 -ne num2 ] Checks if num1 is not equal to num2.

Example1: Check if you are eligble for vote using Bash Numeric Comparison

#Bash Shell Script to check whether you are eligible for voting or not
read -p "Enter your age: " age
if [ $age -ge 18 ]
then
  echo "You are eligible for voting."
else
  echo "You are not eligible for voting."
fi

Output of the above program

Enter your age: 35
You are eligible for voting.
Enter your age: 15
You are not eligible for voting.

Example2: Check a given year is a leap year or not using Bash Numeric Comparison

read -p "Enter a year: " year
if [ $((year%4)) -eq 0 ]
then
  if [ $((year%100)) -eq 0 ]
  then
    if [ $((year%400)) -eq 0 ]
    then
      leap=1
    else
      leap=0
    fi
  else
    leap=1
  fi
else
  leap=0
fi
if [ $leap -eq 1 ]
then
  echo "$year is a leap year."
else
  echo "$year is not a leap year."
fi

Output of the above program

Enter a year: 1990
1990 is not a leap year.
Enter your age: 2004
2004 is a leap year.

Check out these related Bash Shell Tutorial