Explanation
1. Purpose
This Bash script asks the user to enter three numbers, compares them using conditional logic, and displays the largest number among them.
2. Key Concepts
- User Input (
read -p): Prompts the user and stores their response in a variable. - Conditional Logic (
if/elif/else): Executes different code blocks based on specific conditions. - Integer Comparison Operator (
-ge): Checks if a number is "greater than or equal to" another. - Logical Operator (
&&): Represents the "AND" operation, requiring both conditions to be true.
3. Code Walkthrough
-
Getting Input:
read -p "Enter the first number: " num1Prompts the user three separate times and saves the numbers into variables:
num1,num2, andnum3. -
First Check (
if):if [ "$num1" -ge "$num2" ] && [ "$num1" -ge "$num3" ]; thenChecks if
num1is greater than or equal to bothnum2andnum3. If so, it printsnum1. -
Second Check (
elif):elif [ "$num2" -ge "$num1" ] && [ "$num2" -ge "$num3" ]; thenIf
num1isn't the largest, it checks ifnum2is greater than or equal to bothnum1andnum3. If so, it printsnum2. -
Default Case (
else):else echo "The largest number is: $num3"If neither
num1nornum2is the largest, thennum3must be the largest by default, so it printsnum3.
4. Output
The program outputs a text prompt for each number, followed by the final result.
Example Terminal Session:
Enter the first number: 12
Enter the second number: 45
Enter the third number: 7
The largest number is: 45