Conditional statements in shell script
Continuation of “https://samhith1053.medium.com/operators-in-shell-script-fd47b77be80f”
If statement:
Structure
if [ condition ]; then
Statements to be done if the condition evaluated is true
fi
One practical example for simple if statement is
Printing the maximum of 2 numbers:
The code snippet is attached below:
Output:
If -else statement:
The above program we can modify a bit
We are checking num1 is greater than num2 if the condition is evaluated false 1st if block will not get executed and checking 2nd if block so instead of that if the condition of 1st if block is false we can tell directly that second number is greater
Output:
If else if statement:
The structure of if and else if statement is :
if [ condition ]
then
statements
elif [condition1]
then
Statements in elif
elif [ condition2 ]
then
Statements in elif
else
Statements in else
fi
There can be any number of elif statements
Consider the below example checking if the number is divisible by 10 or divisible by 2 or divisible by 5 or neither of 2 nor 5
Output:
Nested -if statements:
Structure of nested if
if [ condition 1 ]; then
Statements
if [ condition 2 ]; then
Statements in the nested if block — — condition1 and condition2 both are true
else
If the condition 2 is false innermost else statement executed — condition 1 is true but condition 2 is false
fi
else
Statements if the condition 1 is false
Let’s consider a task maximum of 2 numbers from the command line arguments
Snippet is given below:
Output: