Home » Linux/Unix » Linux if-then-else Statement Shell Script Examples for Numeric Comparison

Linux if-then-else Statement Shell Script Examples for Numeric Comparison

The most common test evaluation method is to perform a comparison of two numeric values. In this tutorial, I am giving some Linux if-then-else statement shell script examples for numeric comparison.

The following is the list of Bash shell numeric test operators, which we can use with the if-then-else statement in the shell script.

Bash Shell Numeric Test Operators

Integer ComparisonsFunction
-gtGreater than
-ltLess than
-geGreater than or equal to
-leLess than or equal to
-eqEqual to
-neNot equal to

Linux if-then-else Statement Numeric Comparison Examples

The following shell script will perform multiple if-then-else condition test on the numeric values.

ifnum1.sh

#!/bin/bash

i_a=9
i_b=10
i_c=9


if [ $i_a -eq $i_c ] 
then
   echo "$i_a is equal to $i_c"
   else
   echo "$i_a is not equal to $i_c"
fi

if [ $i_a -ge $i_c ] 
then
   echo "$i_a is greater than or equal to $i_c"
   else
   echo "$i_a is less than from $i_c"
fi

if [ $i_a -gt $i_b ]
then
   echo "$i_a is greater than $i_b."
else
   echo "$i_a is not greater than $i_b."
fi

if [ $i_a -le $i_b ]
then
   echo "$i_a is less than or equal to $i_b."
else
   echo "$i_a is greater than $i_b."
fi

if [ $i_a -lt $i_b ]
then
   echo "$i_a is less than $i_b."
else
   echo "$i_a is greater than $i_b."
fi

if [ $i_a -ne $i_b ]
then
   echo "$i_a is not equal to $i_b."
else
   echo "$i_a is equal to $i_b."
fi

Make the file executable

chmod +x ifnum1.sh

Test

./ifnum1.sh

Output

9 is equal to 9
9 is greater than or equal to 9
9 is not greater than 10.
9 is less than or equal to 10.
9 is less than 10.
9 is not equal to 10.

But if you will try to compare numeric floating-point values, then you won't get the result due to the limitation of bash shell floating-point testing. Below is an example:

ifnum2.sh

#!/bin/bash

f_var=9.99
f_var2=9.99

if [ $f_var -eq $f_var2 ]
then
   echo "It is equal."
   else
   echo "It is not equal."
fi

Make executable

chmod +x ifnum2.sh

Test

./ifnum2.sh

Output

./ifnum2.sh: line 6: [: 9.99: integer expression expected
It is not equal.

See even it is equal, but not able to successfully compare. Remember that the only numbers the bash shell can handle are integers. This works fine if you will display it, using echo command.

See also: