Decision
Making
In
programming, Decision Making is one of the important concepts. The programmer
provides one or more conditions for the execution of a block of code. If the
conditions are satisfied then those block of codes only gets executed.
Two types of
decision-making statements are used within shell scripting. They are –
1.
If-else statement:
If else
statement is a conditional statement. It can be used to execute two different
codes based on whether the given condition is satisfied or not.
There are a
couple of varieties present within the if-else statement. They are –
- if-fi
- if-else-fi
- if-elif-else-fi
- nested if-else
The syntax
for the simplest one will be –
Syntax of
If-else statement:
if [ expression ]; then
statements
fi
Example
Script:
Name="Satyajit"
if [ "$Name" = "Satyajit" ]; then
echo "His name is Satyajit. It is true."
fi
Output of
if-else statement:
His name is Satyajit. It is true.
In the above
example, during the condition checking the name matches and the condition
becomes true. Hence, the block of code present within the if block gets
executed. In case the name doesn’t match then will not have an output. Below is
the terminal shell pictorial depiction after executing the following script --

2.
case-sac statement:
case-sac is
basically working the same as switch statement in programming. Sometimes if we
have to check multiple conditions, then it may get complicated using if
statements. At those moments we can use a case-sac statement. The syntax will
be –
Syntax of case-sac statement:
case $var in
Pattern 1) Statement 1;;
Pattern n) Statement n;;
esac
Example
Script:
Name="Satyajit"
case "$Name" in
#case 1
"Rajib") echo "Profession : Software Engineer" ;;
#case 2
"Vikas") echo "Profession : Web Developer" ;;
#case 3
"Satyajit") echo "Profession : Technical Content Writer" ;;
esac
Output of
case-sac statement:
Profession : Technical Content Writer
In the above
example, the case-sac statement executed the statement which is a part of the
matched pattern here the ‘Name’. Below is the terminal shell pictorial
depiction after executing the following script –

No comments:
Post a Comment