Find Largest of Two Numbers in Bash

In this tutorial, you will learn how to find the largest of two numbers in a Bash script using if-else conditional statement with the comparison operators.


Using If-Else Statement to Find the Largest of Two Numbers

The simplest way to find the largest of two numbers in Bash is by using an if-else statement with the condition to check if first number is greater than or equal to the second number. If the condition is true, we know that the first number is the largest, or if the condition is false, we know that the second number is the largest.

The -ge operator is used in Bash to compare two numbers. The -ge operator stands for “greater than or equal to” and checks whether the first number is greater than or equal to the second number.

Here’s an example that uses the -ge operator to find the largest of two numbers in an if-else statement:

largest_number.sh

</>
Copy
#!/bin/bash
# Define two numbers
num1=10
num2=5

# Compare the two numbers and find the largest
if [ $num1 -ge $num2 ]; then
  echo "$num1 is the largest number."
else
  echo "$num2 is the largest number."
fi

Explanation:

  1. Defining two numbers: Two variables, num1 and num2, are initialized with the values 10 and 5, respectively.
  2. Comparing the two numbers: The if condition uses the -ge (greater than or equal to) operator to compare num1 and num2:
    • If num1 is greater than or equal to num2, the condition evaluates to true.
    • Otherwise, the condition evaluates to false, and the script executes the else block.
  3. Printing the largest number:
    • If the condition is true, the script prints "$num1 is the largest number." using the echo command.
    • If the condition is false, the script prints "$num2 is the largest number.".
  4. End of script: The script ends after successfully determining and displaying the largest number.

Output

10 is the largest number.

Now, let’s modify the script to accept user input for the two numbers. This makes the script more dynamic and allows the user to enter any pair of numbers to find the largest.

Here’s the modified version of the script:

largest_number.sh

</>
Copy
#!/bin/bash
# Prompt the user to enter two numbers
echo "Enter the first number:"
read num1
echo "Enter the second number:"
read num2

# Compare the two numbers and find the largest
if [ $num1 -ge $num2 ]; then
  echo "$num1 is the largest number."
else
  echo "$num2 is the largest number."
fi

Explanation:

  1. Prompt the user for input:
    • The script prompts the user to enter the first number using echo "Enter the first number:" and reads the input into the variable num1 using the read command.
    • It then prompts the user to enter the second number using echo "Enter the second number:" and reads the input into the variable num2.
  2. Rest of the steps are same as that of the previous program.

Example Output:

Enter the first number:
8
Enter the second number:
15
15 is the largest number.