Lecture # 4 - Decision Making in Shell Script

Lecture # 4 - Decision Making in Shell Script

if Statement, if-else Statement, if-elif-else Statement

Decision Making in Shell Script:

Decision making in shell scripting is typically achieved using conditional statements. The most commonly used conditional statements in shell scripting are the if, elif (optional), and else statements.

if Statement:

The if statement allows you to execute a block of code if a specified condition is true. Its syntax is:

if [ condition ]
then
    # Commands to be executed if condition is true
fi

if-else Statement:

The if-else statement allows you to execute one block of code if a condition is true and another block of code if the condition is false. Its syntax is:

if [ condition ]
then
    # Commands to be executed if condition is true
else
    # Commands to be executed if condition is false
fi

if-elif-else Statement:

The if-elif-else statement allows you to evaluate multiple conditions sequentially and execute different blocks of code based on the first condition that evaluates to true. The elif part is optional and can be repeated as needed. Its syntax is:

if [ condition-1 ]
then
    # Commands to be executed if condition-1 is true
elif [ condition-2 ]
then
    # Commands to be executed if condition-2 is true
else
    # Commands to be executed if all conditions are false
fi