0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Find Largest of Two Numbers

Use a Bash script with an if statement to compare two numbers and print the larger one, like if [ $a -gt $b ]; then echo $a; else echo $b; fi.
📋

Examples

Inputa=5, b=3
Output5
Inputa=10, b=10
Output10
Inputa=-2, b=7
Output7
🧠

How to Think About It

To find the largest of two numbers, compare them using the greater-than operator -gt in Bash. If the first number is greater or equal, print it; otherwise, print the second number.
📐

Algorithm

1
Get the first number as input and store it in variable a
2
Get the second number as input and store it in variable b
3
Compare if a is greater than or equal to b
4
If yes, print a
5
Otherwise, print b
💻

Code

bash
#!/bin/bash
read -p "Enter first number: " a
read -p "Enter second number: " b
if [ $a -ge $b ]; then
  echo "$a is the largest number"
else
  echo "$b is the largest number"
fi
Output
Enter first number: 8 Enter second number: 3 8 is the largest number
🔍

Dry Run

Let's trace the input a=8 and b=3 through the code

1

Input values

a=8, b=3

2

Compare a and b

Is 8 >= 3? Yes

3

Print result

Print '8 is the largest number'

StepabCondition (a >= b)Output
183true8 is the largest number
💡

Why This Works

Step 1: Read inputs

The script uses read to get two numbers from the user and stores them in variables a and b.

Step 2: Compare numbers

The if [ $a -ge $b ] checks if a is greater than or equal to b using the numeric comparison operator -ge.

Step 3: Print largest

If the condition is true, it prints a; otherwise, it prints b, showing the largest number.

🔄

Alternative Approaches

Using ternary-like syntax with && and ||
bash
read -p "Enter first number: " a
read -p "Enter second number: " b
[ $a -ge $b ] && echo "$a is the largest number" || echo "$b is the largest number"
This is shorter but less readable for beginners.
Using arithmetic expansion
bash
read -p "Enter first number: " a
read -p "Enter second number: " b
max=$(( a > b ? a : b ))
echo "$max is the largest number"
Uses Bash arithmetic to find max in one line, good for compact scripts.

Complexity: O(1) time, O(1) space

Time Complexity

The script performs a single comparison operation, so it runs in constant time regardless of input size.

Space Complexity

Only a few variables are used to store inputs and results, so space usage is constant.

Which Approach is Fastest?

All approaches run in constant time; using arithmetic expansion is slightly more concise but functionally equivalent.

ApproachTimeSpaceBest For
if-else statementO(1)O(1)Clear and beginner-friendly
&& and || operatorsO(1)O(1)Short scripts, less readable
Arithmetic expansionO(1)O(1)Compact code, slightly advanced
💡
Always quote variables in Bash to avoid errors with spaces or empty inputs.
⚠️
Forgetting to use numeric comparison operators like -gt or -ge and using string comparison instead.