In shell scripting, you can implement decision-making using conditional statements. The most common conditional statements in shell scripting are if
, elif
(short for "else if"), and else
. These statements allow you to execute different code blocks based on whether certain conditions are met.
Uses of these conditional statements in shell scripts:
The if
Statement:
if
statement is used to test a condition and execute a block of code if the condition is true.if [ $x -eq 10 ]; then
echo "x is equal to 10"
fi
[ ]
to check conditions. For example:
if [ $x -eq 10 ]; then
echo "x is equal to 10"
fi
The elif
Statement:
elif
statement allows you to test multiple conditions in a sequential manner.if
or elif
conditions are false, the code block associated with the first true condition is executed.if [ condition1 ]; then
# Code to execute if condition1 is true
elif [ condition2 ]; then
# Code to execute if condition2 is true
else
# Code to execute if none of the conditions are true
fi
The else
Statement:
else
statement is used to provide a default code block to execute when none of the preceding conditions are true.if
or elif
to handle cases where none of the conditions match.else
block is optional.if [ $x -eq 10 ]; then
echo "x is equal to 10"
else
echo "x is not equal to 10"
fi
Logical Operators:
-eq
(equal), -ne
(not equal), -lt
(less than), -le
(less than or equal), -gt
(greater than), -ge
(greater than or equal), &&
(logical AND), and ||
(logical OR) to form complex conditions.if [ $x -eq 10 ] && [ $y -lt 20 ]; then
echo "x is 10 and y is less than 20"
fi
Nested if
Statements:
if
statements within other if
statements to create more complex decision structures.if [ $x -eq 10 ]; then
if [ $y -lt 20 ]; then
echo "Both conditions are true"
fi
fi
Here's a complete example of a shell script that uses if
, elif
, and else
statements to make decisions based on user input:
#!/bin/bash
echo "Enter a number: "
read num
if [ $num -gt 0 ]; then
echo "The number is positive."
elif [ $num -lt 0 ]; then
echo "The number is negative."
else
echo "The number is zero."
fi
This script takes user input and determines whether the entered number is positive, negative, or zero based on the conditions specified.
The if...else statement as follows −
Output:
The if...elif...fi statement is the one level advance form of control statement that allows Shell to make correct decision out of several conditions.
The if..elif..else..fi statement as follows −
Output:
Enroll Now