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. Different blocks of code execute depending on whether a condition is true or false.

In shell scripting, conditions are commonly written usingif,elif, andelse.

Why Use Conditional Statements?

Decision Making

Control script flow based on conditions.

Automation

Scripts respond dynamically to user input and data.

Error Handling

Handle success and failure conditions properly.

Syntax of if, elif, else

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

Comparison Operators

Numeric Comparison Operators

OperatorMeaning
-eqEqual to
-neNot equal to
-gtGreater than
-ltLess than
-geGreater than or equal to
-leLess than or equal to

String Comparison Operators

OperatorMeaning
=Strings are equal
!=Strings are not equal
-zString is empty
-nString is not empty

File Test Operators

OperatorMeaning
-fCheck if file exists
-dCheck if directory exists
-rCheck read permission
-wCheck write permission
-xCheck execute permission

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

5. File Check Example

Check whether a file exists.

terminal — bash
if-else
file="test.txt"
 
if [ -f "$file" ]; then
echo "File exists"
else
echo "File not found"
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.
  • Use meaningful conditions.
  • Test scripts with different inputs.

Practice Task – Conditional Logic

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

Next lesson: Loops (for, while, until)