Class 20 of 37 • Advance Shell Script \t\t\t\t

Conditional Statements in Linux Shell Scripting - if, elif, else & case

Condition is a comparison between two values.for compression you can use test or [expr] statements or even exist status can be also used.expression is defined as - an expression is nothing but combination of values,relational operator (>,<,<>) and mathematical operator (+,-,/).there are the following kinds of statements available in shell programming as decision making statements.

1. The simple "if" Statement

simple if is used for decision making in shell script.if the given condition is true then it will execute the set of code that you have allocated to that block.

Syntax


if [ condition ]	
then
      # Execute statements when condition evaluates to TRUE (exit code 0)
      command1
      command2
fi
							

Example


#!/bin/bash
# Check if number entered is equal to 1

echo -n "Enter a Number: "
read no

# Note: space is mandatory after [ and before ]
if [ "$no" -eq 1 ]	
then
      echo "You entered Number 1"
fi
							

2. The "if..else" Statement

if..else is used for decision making in shell script where the given condition is true then it will execute the set of code that you have allocated to that block otherwise you can execute the rest of code for the false condition.

Syntax


if [ condition ]
then
    # Execute if condition is TRUE
    command_if_true
else
    # Execute if condition is FALSE
    command_if_false
fi	
							

Example


#!/bin/bash
# Check if number is positive or negative

echo -n "Enter Number: "
read no

if [ "$no" -gt 0 ]
then
    echo "$no is Positive"
else
    echo "$no is Negative or Zero"
fi
							

3. The "if..elif..else" Statement

it is possible to create compound conditional statements by using one or more else if(elif) clause.if the 1st condition is false,then subsequent elif statements are checked.when an elif condition is found to be true,the statements following that associated parts are executed.

Syntax


if [ condition1 ]
then
    statements_1
elif [ condition2 ]
then
    statements_2
elif [ condition3 ]
then
    statements_3
else
    fallback_statements
fi
							

Example


#!/bin/bash
# Determine student grade based on percentage marks

echo -n "Enter Student Marks (0-100): "
read marks

if [ "$marks" -ge 80 ]
then
    echo "Grade: Distinction (A+)"
elif [ "$marks" -ge 60 ]
then
    echo "Grade: First Class (A)"
elif [ "$marks" -ge 40 ]
then
    echo "Grade: Second Class (B)"
else
    echo "Grade: Fail - Needs Improvement"
fi
							

Essential File Test Comparison Operators

In Linux system administration and shell scripting, verifying file properties before performing operations is critical. Use these file test operators inside [ ... ]:

Operator Condition Tested Practical Code Example
-e file True if file exists (regardless of type). [ -e /etc/hosts ]
-f file True if file exists and is a regular file (not a directory or device). [ -f script.sh ]
-d dir True if target exists and is a directory. [ -d /var/log ]
-r file True if file is readable by current user. [ -r database.conf ]
-w file True if file is writable by current user. [ -w output.txt ]
-x file True if file is executable. [ -x /bin/bash ]
-s file True if file exists and has size greater than 0 bytes (not empty). [ -s report.csv ]

4. The "case..esac" Statement

The case statement is ideal for building interactive menus and evaluating multiple branches against patterns. It is much cleaner and faster than long chains of elif statements:

Syntax


case "$variable" in
    pattern1)
        command1 ;;
    pattern2|pattern3)
        command2 ;;
    *)
        default_fallback_command ;;
esac
							

Menu-Driven Practical Program (BCA Exam Special)


#!/bin/bash
# ==========================================================
# Script Name : menu_calc.sh
# Description : Menu-driven arithmetic calculator using case
# ==========================================================

clear
echo "----------------------------------------"
echo "      LINUX MENU-DRIVEN CALCULATOR      "
echo "----------------------------------------"
echo "1. Display Current Date & Time"
echo "2. List Files in Current Directory"
echo "3. Check Free Disk Space"
echo "4. Show Logged-in Users"
echo "5. Exit"
echo "----------------------------------------"
echo -n "Enter Choice (1-5): "
read choice

case "$choice" in
    1)
        echo "Date: $(date)" ;;
    2)
        echo "Files: "
        ls -la ;;
    3)
        df -h / ;;
    4)
        who ;;
    5)
        echo "Exiting... Goodbye!"
        exit 0 ;;
    *)
        echo "Invalid Choice! Please enter 1 to 5." ;;
esac
							

Frequently Asked Questions (FAQ)

Inside POSIX single brackets [ ... ], use -a for logical AND, and -o for logical OR (e.g., [ "$a" -gt 0 -a "$b" -gt 0 ]). In modern Bash double brackets [[ ... ]], use standard C-style operators && and || (e.g., [[ $a -gt 0 && $b -gt 0 ]]).

Use the -z operator: if [ -z "$my_string" ]; then echo "String is empty"; fi. To check if a string is NOT empty, use the -n operator.

Next Step in Your Linux Learning Path:

Automate repetitive tasks with for, while, and until loops in Class 21: Looping Statements.

Continue to Class 21: Looping Statements → Previous: ← Operators | Full Syllabus

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!