The Logic of Choice: If-Else and Case Statements
·TechSoftware Development

The Logic of Choice: If-Else and Case Statements

Give your scripts a brain. Master the logic of decision making in Bash. Learn to use If-Else blocks, perform File Tests, compare strings/numbers, and use 'Case' statements for complex multi-choice scenarios.

Control Flow: Making Decisions in the Shell

Up until now, our scripts have been "Linear"—one command after another. But real-world automation needs to handle different situations.

  • IF the file exists, delete it.
  • IF the user is root, run the update.
  • IF the disk is 90% full, send an alert.

In this lesson, we will learn how to add logic to your scripts using if statements and case blocks.


1. The If-Else Structure

The syntax of a Bash if statement is strict. It relies on the code between the [ and ] brackets (which is actually a command called test).

if [ condition ]; then
    # Do this if true
else
    # Do this if false
fi

Pro Tip: You MUST have spaces inside the brackets. [ condition ] is correct; [condition] will fail.


2. The Three Types of Tests

I. Numeric Comparisons

  • -eq: Equal
  • -ne: Not equal
  • -gt: Greater than
  • -lt: Less than
if [ $AGE -gt 18 ]; then
    echo "Access granted."
fi

II. String Comparisons

  • =: Equal
  • !=: Not equal
  • -z: Is empty (zero length)
if [ "$USER" = "root" ]; then
    echo "You are an admin."
fi

III. File Tests (The SysAdmin's Best Friend)

  • -f: Exists and is a regular file.
  • -d: Exists and is a directory.
  • -e: Exists (general).
  • -x: Exists and is executable.
if [ -f "/etc/passwd" ]; then
    echo "Critical file found."
fi

3. Complex Choices: Elif and Case

Elif (Else If)

Used for checking multiple conditions in order.

if [ $SCORE -ge 90 ]; then
    echo "A"
elif [ $SCORE -ge 80 ]; then
    echo "B"
else
    echo "F"
fi

Case (The Switch Statement)

Used when you have a single variable and many possible values. It's much cleaner than 10 if statements.

case $COLOR in
    "red")
        echo "Stop"
        ;;
    "green")
        echo "Go"
        ;;
    *)
        echo "Unknown"
        ;;
esac

4. Practical: The "Smart Backup" Script

Let's combine these into a script that only performs a backup if the disk has space.

#!/bin/bash

DEST="/backups/data.tar.gz"

if [ -f "$DEST" ]; then
    echo "Backup already exists. Aborting to prevent overwrite."
    exit 1
fi

DISK_FREE=$(df / | tail -1 | awk '{print $4}')

if [ $DISK_FREE -lt 1000000 ]; then
    echo "CRITICAL: Not enough disk space (< 1GB)!"
    exit 1
else
    echo "Space check passed. Starting backup..."
    tar -czf "$DEST" /home/sudeep/data
fi

5. Example: A Logic Integrity Validator (Python)

Bash syntax for if statements is often confusing (is it -gt or >?). Here is a Python script that acts as a "syntax trainer." It generates a logic scenario and checks if you can translate it into a valid Bash condition.

import random

def logic_quiz():
    """
    Generates a simple logic scenario to test terminal knowledge.
    """
    scenarios = [
        {"desc": "Check if variable X is greater than 100", "bash": "[ $X -gt 100 ]"},
        {"desc": "Check if file 'data.csv' exists", "bash": "[ -f data.csv ]"},
        {"desc": "Check if variable USER is NOT 'root'", "bash": "[ \"$USER\" != \"root\" ]"},
        {"desc": "Check if directory '/tmp' exists", "bash": "[ -d /tmp ]"}
    ]
    
    item = random.choice(scenarios)
    print(f"How do you write this in Bash?")
    print(f"Scenario: {item['desc']}")
    
    input("\nPress Enter to see the correct syntax...")
    print(f"\nCorrect Syntax: {item['bash']}")
    print("Remember: Spaces inside the [ ] are mandatory!")

if __name__ == "__main__":
    logic_quiz()

6. Professional Tip: Use Double Brackets [[ ]]

If you are using Bash (and not the older POSIX sh), always use [[ ]] instead of [ ].

  • It is faster.
  • It doesn't crash if a variable is empty.
  • It supports pattern matching (like [[ $NAME == s* ]]).

7. Summary

Control flow gives your automation a "Voice" and a "Mind."

  • if ... then ... else ... fi is the standard logic block.
  • File Tests (-f, -d) are essential for robust scripts.
  • -eq is for numbers; = is for strings.
  • case makes multi-choice scripts readable.
  • Always quote your variables (e.g., "$VAR") to prevent script crashes.

In the next lesson, we will learn how to perform repetitive tasks using Loops (For and While).

Quiz Questions

  1. Why do we put double quotes around variables in an if statement (e.g., [ "$VAR" = "hi" ])?
  2. What is the difference between -eq and =?
  3. Which flag do you use to check if a path is a directory?

Continue to Lesson 4: Loops—For, While, and Until.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn