Bash Script to Find Largest of Three Numbers
if statements to compare three numbers and print the largest, like: if [ "$a" -ge "$b" ] && [ "$a" -ge "$c" ]; then echo $a; elif [ "$b" -ge "$a" ] && [ "$b" -ge "$c" ]; then echo $b; else echo $c; fi.Examples
How to Think About It
if conditions. If it is greater or equal to both, it is the largest. Otherwise, compare the second number similarly. If neither the first nor second is largest, the third must be the largest.Algorithm
Code
#!/bin/bash a=5 b=3 c=9 if [ "$a" -ge "$b" ] && [ "$a" -ge "$c" ]; then echo "$a" elif [ "$b" -ge "$a" ] && [ "$b" -ge "$c" ]; then echo "$b" else echo "$c" fi
Dry Run
Let's trace the example where a=5, b=3, c=9 through the code
Compare a with b and c
Check if 5 >= 3 and 5 >= 9 (false because 5 is not >= 9)
Compare b with a and c
Check if 3 >= 5 and 3 >= 9 (false because 3 is not >= 5)
Else case
Since neither a nor b is largest, print c which is 9
| Step | Condition | Result |
|---|---|---|
| 1 | 5 >= 3 and 5 >= 9 | false |
| 2 | 3 >= 5 and 3 >= 9 | false |
| 3 | Print c | 9 |
Why This Works
Step 1: Compare first number
The script uses -ge to check if the first number is greater than or equal to the other two.
Step 2: Compare second number
If the first is not largest, it checks if the second number is greater than or equal to the others.
Step 3: Default to third number
If neither first nor second is largest, the script prints the third number as the largest.
Alternative Approaches
#!/bin/bash a=5 b=3 c=9 if [ "$a" -ge "$b" ]; then if [ "$a" -ge "$c" ]; then echo "$a" else echo "$c" fi else if [ "$b" -ge "$c" ]; then echo "$b" else echo "$c" fi fi
#!/bin/bash nums=(5 3 9) largest=${nums[0]} for num in "${nums[@]}"; do if [ "$num" -gt "$largest" ]; then largest=$num fi done echo "$largest"
Complexity: O(1) time, O(1) space
Time Complexity
The script performs a fixed number of comparisons (3), so it runs in constant time O(1).
Space Complexity
It uses a few variables and no extra data structures, so space complexity is O(1).
Which Approach is Fastest?
All approaches run in constant time; using direct comparisons is simplest, while loops add flexibility for more numbers.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct if-else | O(1) | O(1) | Simple fixed number comparisons |
| Nested if-else | O(1) | O(1) | Clearer logic for beginners |
| Loop with array | O(n) | O(n) | Finding largest in many numbers |
-ge or mixing up numeric and string comparisons causes wrong results.