</>
Skip to content
Bash lessons (11/29)

Bash — If Else

Basic if

#!/bin/bash

x=10

if [ $x -gt 5 ]; then
    echo "x is greater than 5"
fi

if-else

#!/bin/bash

x=3

if [ $x -gt 5 ]; then
    echo "x is greater than 5"
else
    echo "x is not greater than 5"
fi

if-elif-else

#!/bin/bash

score=85

if [ $score -ge 90 ]; then
    echo "Grade: A"
elif [ $score -ge 80 ]; then
    echo "Grade: B"
elif [ $score -ge 70 ]; then
    echo "Grade: C"
else
    echo "Grade: F"
fi

case statement

#!/bin/bash

day="Monday"

case $day in
    Monday)
        echo "Start of week"
        ;;
    Friday)
        echo "Almost weekend"
        ;;
    Saturday|Sunday)
        echo "Weekend!"
        ;;
    *)
        echo "Midweek"
        ;;
esac

Combining conditions

#!/bin/bash

age=25
income=50000

if [ $age -ge 18 ] && [ $income -ge 30000 ]; then
    echo "Qualifies for premium"
fi

if [ $age -lt 12 ] || [ $age -gt 65 ]; then
    echo "Discounted ticket"
fi

File checks

#!/bin/bash

file="test.txt"

if [ -f "$file" ]; then
    echo "File exists"
elif [ -d "$file" ]; then
    echo "Directory exists"
else
    echo "Not found"
fi

Mini Practice

Write Bash code that:

  1. Uses if-elif-else for grade classification
  2. Uses case for day of week
  3. Combines conditions with && and ||
  4. Checks if a file exists

Up Next

In the next lesson, you'll learn about For Loops — iterating with for in Bash.

Related Topics

Frequently Asked Questions about If Else

What is If Else in Bash?

If Else is a fundamental concept in Bash. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn If Else?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn If Else.

Why is If Else important in Bash?

If Else is essential for Bash development. Understanding this concept will help you write better code and solve real-world problems more effectively.