Bash Conditional Statements

Conditional statements allow a script to make decisions. Based on a condition, the script chooses which block of code to run. This is how scripts become smart — they check a situation and respond accordingly.

if Statement

The simplest form of a decision. If the condition is true, run the code inside.

Syntax

if [ condition ]
then
  # commands to run if condition is true
fi

Example

#!/bin/bash
temp=38
if [ $temp -gt 37 ]
then
  echo "Temperature is high. Take rest."
fi

Output:

Temperature is high. Take rest.

if-else Statement

When there are two possible outcomes, use if-else. If the condition is true, run the first block. If it is false, run the else block.

if [ condition ]
then
  # runs when condition is true
else
  # runs when condition is false
fi

Example

#!/bin/bash
score=45
if [ $score -ge 50 ]
then
  echo "Result: Pass"
else
  echo "Result: Fail"
fi

Output:

Result: Fail

if-elif-else Statement

When there are more than two possible outcomes, chain multiple conditions using elif (short for else if).

if [ condition1 ]
then
  # runs when condition1 is true
elif [ condition2 ]
then
  # runs when condition2 is true
else
  # runs when no condition is true
fi

Example – Grade Checker

#!/bin/bash
marks=72
if [ $marks -ge 90 ]
then
  echo "Grade: A+"
elif [ $marks -ge 75 ]
then
  echo "Grade: A"
elif [ $marks -ge 60 ]
then
  echo "Grade: B"
elif [ $marks -ge 50 ]
then
  echo "Grade: C"
else
  echo "Grade: F (Fail)"
fi

Output:

Grade: B

Decision Flow Diagram

┌─────────────────────────────────────────────────┐
│            if-elif-else Flow                    │
│                                                 │
│  Check condition1                               │
│       │                                         │
│    TRUE ──► Run block1                          │
│    FALSE                                        │
│       │                                         │
│  Check condition2                               │
│       │                                         │
│    TRUE ──► Run block2                          │
│    FALSE                                        │
│       │                                         │
│  else ──► Run default block                     │
└─────────────────────────────────────────────────┘

Nested if Statements

An if block can contain another if block inside it. This is called nesting.

#!/bin/bash
age=20
country="India"

if [ $age -ge 18 ]
then
  if [ "$country" = "India" ]
  then
    echo "Eligible to vote in India."
  else
    echo "Eligible to vote in your country."
  fi
else
  echo "Not eligible to vote."
fi

Output:

Eligible to vote in India.

case Statement

The case statement is a cleaner way to handle multiple fixed values. It works like a list of choices. Bash checks the variable against each pattern and runs the matching block.

Syntax

case $variable in
  pattern1)
    # commands
    ;;
  pattern2)
    # commands
    ;;
  *)
    # default if nothing matches
    ;;
esac

Example – Day of the Week

#!/bin/bash
day="Monday"

case $day in
  Monday)
    echo "Start of the work week."
    ;;
  Friday)
    echo "Last working day. Weekend is near!"
    ;;
  Saturday | Sunday)
    echo "It is the weekend."
    ;;
  *)
    echo "Regular weekday."
    ;;
esac

Output:

Start of the work week.

Example – Menu Selection

#!/bin/bash
read -p "Choose option (1/2/3): " choice

case $choice in
  1) echo "Option 1: View files" ;;
  2) echo "Option 2: Create file" ;;
  3) echo "Option 3: Exit" ;;
  *) echo "Invalid option" ;;
esac

Using Double Brackets [[ ]]

Double brackets [[ ]] are an enhanced version of single brackets [ ]. They support more features and are generally safer to use in modern Bash scripts.

FeatureSingle [ ]Double [[ ]]
Pattern matchingNoYes (with *)
Regex matchingNoYes (with =~)
String comparisonBasicMore reliable
AND / OR inside-a / -o&& / ||
#!/bin/bash
name="Ravi"
if [[ "$name" == R* ]]; then
  echo "Name starts with R"
fi

Output:

Name starts with R

Ternary-style Shorthand

Bash does not have a built-in ternary operator like some languages, but the && and || pattern achieves a similar effect.

#!/bin/bash
x=10
[ $x -gt 5 ] && echo "Greater than 5" || echo "Not greater than 5"

Output:

Greater than 5

Practical Example – Login Check

#!/bin/bash
stored_user="admin"
stored_pass="secure123"

read -p "Username: " input_user
read -sp "Password: " input_pass
echo ""

if [[ "$input_user" == "$stored_user" && "$input_pass" == "$stored_pass" ]]; then
  echo "Login successful. Welcome, $input_user!"
else
  echo "Login failed. Invalid credentials."
fi

Key Takeaways

  • Use if for a single condition check.
  • Use if-else for two possible outcomes.
  • Use if-elif-else for multiple conditions in sequence.
  • Use case when checking one variable against several fixed values.
  • Prefer [[ ]] over [ ] in modern Bash scripts for safer and more powerful comparisons.

Leave a Comment