How to Compare Numbers in Bash?

When working with Bash scripting, knowing how to compare numbers effectively is essential. Comparing numbers in Bash can help users to create conditional statements, perform mathematical operations, and much more. This article will discuss how a user can compare numbers in bash script using different examples.

The examples that will be used to compare numbers are listed below:

  • Using the if Statement
  • Using the Nested if Statement
  • Using Loop using a Condition

Method 1: Comparing Numbers using the if Statement

The if statement can be used to compare two numbers, and one of its examples in bash scripting is discussed below:

#!/bin/bash
num1=10
num2=5
if [ $num1 -gt $num2 ]
then
    echo "num1 is greater than num2"
fi

Code Explanation:

  • This script defines two variables, num1 with the value 10 and num2 with the value 5.
  • The -gt operator checks if num1 is greater than num2. 
  • If the condition is true, the script outputs “num1 is greater than num2”.

The output of the code can be seen by executing the bash script mentioned below

$ bash compare_nos.sh

Method 2: Comparing Numbers Using the Nested if Statement

If a user wants to compare the numbers using the nested if statement, then it can be done by following the bash script mentioned below:

#!/bin/bash
num1=10
num2=5
num3=15
if [ $num1 -gt $num2 ]
then
    if [ $num1 -lt $num3 ]
    then
        echo "num1 is between num2 and num3"
    fi
fi

Code Explanation:

  • This script defines three variables, num1, num2, and num3 with different values.
  • The -gt and -lt operators check if num1 is greater than num2 and less than num3. 
  • If the conditions are true, the script outputs “num1 is between num2 and num3”.

The output of the code can be seen by executing the bash script mentioned below:

$ bash compare_nos.sh

Method 3: Comparison in Loop Using a Condition

If a user wants to print all the even numbers only and discard the odd numbers, then this could be possible by writing the below script mentioned below:

#!/bin/bash
for i in {1..10}
do
    if [ $((i % 2)) -eq 0 ]
    then
        echo $i
    fi
done

Code Explanation:

  • This script uses a for loop to iterate over the numbers from 1 to 10. 
  • It uses the % operator to check if the number is even and outputs the even numbers.

The output of the code can be seen by executing the bash script mentioned below:

$ bash compare_nos.sh

Conclusion

Comparing numbers in Bash is essential when creating Bash scripts. It allows you to create conditional statements and perform mathematical operations. In this article, we covered how to compare numbers in Bash using basic and advanced operators and provided examples of how to use them in real-world scenarios.