Chapter 7: Control Flow

7. Chapter 7: Control Flow#

Now that you understand operators (Chapter 6), you can make scripts that make decisions and repeat actions. Control flow is the skeleton of every program: it determines which code runs and when it repeats.

In this chapter, you’ll master:

  • if/elif/else: Execute different code based on conditions

  • case statements: Handle multiple scenarios elegantly

  • Loops (for, while, until): Repeat code until conditions change

  • Loop control: Break, continue, and advanced patterns

With these tools, you’ll transform scripts from linear sequences into intelligent programs.

What You'll Learn

By the end of this chapter, you will be able to:

✓ Write if/elif/else statements to handle multiple conditions ✓ Use case statements for cleaner multi-way branching ✓ Create for loops to iterate over lists and ranges ✓ Create while and until loops for condition-based repetition ✓ Use break and continue for loop control ✓ Process user input with read and script arguments ✓ Build nested conditionals and complex logic ✓ Avoid common control flow pitfalls

Chapter Map

Section

Topic

Key Concepts

0702

if/elif/else & case

Conditionals, multi-way branching

0703

Loops: for, while, until

Iteration, repeat patterns

0704

Loop Control

break, continue, nested loops

0705

User Input & Arguments

read, \(@, \)1, $#, getopts

0706

Lab: Automation Scripts

Hands-on scripting exercises

Why This Matters

Control flow is what makes scripts intelligent and reusable:

  • Conditionals: Handle different scenarios (file exists? user authorized? error occurred?)

  • Loops: Process hundreds of files without repeating code

  • Decision logic: Make scripts adapt to their environment

  • Automation: Transform manual tasks into automated workflows

  • DevOps: Build deployment scripts, monitoring tools, system maintenance

Real-world examples:

  • Backup script: Loop through files, check conditions, copy if needed

  • Monitoring script: Check metrics in a loop, alert if thresholds exceeded

  • Installer script: Ask user questions, make decisions, configure accordingly

Prerequisites

You should already understand:

  • Variables and variable expansion (Chapter 5)

  • Operators and how to form conditions (Chapter 6)

  • How to run bash scripts

  • Basic command-line navigation

If operators feel unclear, review Chapter 6 first.

Real-World Scenario

You need to process log files from multiple servers and generate a report:

#!/bin/bash

# Loop through each server
for server in web01 web02 db01 cache01; do
    echo "Processing $server..."
    
    # Check if server is reachable
    if ping -c 1 "$server" &> /dev/null; then
        # Download and process logs
        scp "user@$server:/var/log/app.log" "./${server}.log"
        
        # Count errors
        error_count=$(grep -c "ERROR" "${server}.log")
        
        if [ $error_count -gt 100 ]; then
            echo "⚠️  $server has $error_count errors - INVESTIGATE"
        elif [ $error_count -gt 0 ]; then
            echo "✓ $server has $error_count errors - monitor"
        else
            echo "✓ $server is clean"
        fi
    else
        echo "✗ $server is unreachable"
    fi
done

This script uses loops, conditionals, and decision logic—all covered in this chapter.

Sample Script: User Account Provisioning

A realistic script that provisions user accounts with validation:

#!/bin/bash

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color

echo "=== User Account Provisioning Tool ==="

# Validate input
read -p "Enter username: " username
read -p "Enter full name: " fullname
read -s -p "Enter password: " password
echo

# Check if username already exists
if id "$username" &>/dev/null; then
    echo -e "${RED}ERROR: User $username already exists${NC}"
    exit 1
fi

# Validate username format
if ! [[ "$username" =~ ^[a-z][a-z0-9_-]{2,15}$ ]]; then
    echo -e "${RED}ERROR: Invalid username format${NC}"
    exit 1
fi

# Create user
sudo useradd -c "$fullname" -m "$username"
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ User account created${NC}"
else
    echo -e "${RED}ERROR: Failed to create user${NC}"
    exit 1
fi

# Set password
echo "$username:$password" | sudo chpasswd
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Password set${NC}"
else
    echo -e "${RED}ERROR: Failed to set password${NC}"
    exit 1
fi

# Configure groups
groups_to_add=("docker" "sudo" "staff")
for group in "${groups_to_add[@]}"; do
    if getent group "$group" &>/dev/null; then
        sudo usermod -aG "$group" "$username"
        echo -e "${GREEN}✓ Added to $group group${NC}"
    else
        echo -e "${RED}WARNING: Group $group does not exist${NC}"
    fi
done

# Create home directory structure
for dir in Documents Downloads Projects; do
    mkdir -p "/home/$username/$dir"
    sudo chown "$username:$username" "/home/$username/$dir"
done
echo -e "${GREEN}✓ Home directories created${NC}"

# Verify account
echo
echo "=== Account Summary ==="
id "$username"
echo -e "${GREEN}✓ Account provisioning complete!${NC}"

What this script demonstrates:

  • Conditionals: Checking if user exists, validating input

  • Error handling: Using $? to check command success

  • Loops: Processing multiple groups

  • User input: Reading username and password

  • Real-world logic: Practical account provisioning

Progression

This chapter completes the core scripting fundamentals:

Level

Chapters

Focus

Beginner

1-5

Fundamentals: shell, files, variables

Intermediate

6-7

Operators and control flow

Advanced

8-15

Functions, automation, error handling

After this chapter, you’ll have the foundation to write real-world scripts. Chapters 8+ add professional techniques.