Shell Script · Conditional Statements

Shell Scripting · Lesson 8

Conditional Statements

Use if else conditions in shell scripting. Compare numbers and strings. Test command and operators. Build decision making logic like real projects.

What is a Conditional Statement?

Conditional statements allow a script to make decisions based on conditions. The script executes different blocks of code depending on whether a condition is true or false.

Why Use Conditional Statements?

Decision Making

Control the flow of execution based on conditions.

Automation

Scripts can respond differently based on inputs.

Error Handling

Handle success and failure cases properly.

Syntax of if, elif, else

syntax
syntax
if [ condition ]; then
commands
elif [ another_condition ]; then
commands
else
commands
fi

Examples

1. Basic if Statement

Executes a block of code only if the condition is true.

terminal — bash
if-else
age=18
 
if [ $age -ge 18 ]; then
echo "You are eligible to vote"
fi

2. if-else Statement

Executes one block if condition is true, otherwise another.

terminal — bash
if-else
age=15
 
if [ $age -ge 18 ]; then
echo "You can vote"
else
echo "You are not eligible to vote"
fi

3. if-elif-else Statement

Used when checking multiple conditions.

terminal — bash
if-else
marks=75
 
if [ $marks -ge 90 ]; then
echo "Grade A"
elif [ $marks -ge 60 ]; then
echo "Grade B"
else
echo "Grade C"
fi

4. String Comparison Example

Compare strings using = or != operators.

terminal — bash
if-else
name="admin"
 
if [ "$name" = "admin" ]; then
echo "Welcome Admin"
else
echo "Access Denied"
fi

Best Practices

Follow These Rules

  • Always leave space after [ and before ].
  • Use double quotes around variables.
  • Indent code for readability.
  • Use elif instead of multiple if statements.

Practice Task – Conditional Logic

  • Ask user for age and check eligibility.
  • Check if a number is positive or negative.
  • Check username and allow access.

Next lesson: Loops (for, while, until)