NANDHOO.

Chapter 8: Loops

Loops allow you to perform repetitive tasks with precision. In shell scripting, you can iterate over lists of strings, numeric ranges, or the lines of a file. Mastering loops is the key to scaling your automation from single files to entire server clusters.

I. The for Loop: Iterating over Lists

The for loop is most commonly used when you have a known set of items.

1. Basic List Iteration

for OS in Linux macOS Windows BSD; do
    echo "Support for $OS: Yes"
done

2. Numeric Ranges (Brace Expansion)

# Print numbers 1 through 10
for i in {1..10}; do
    echo "Loop #$i"
done

3. C-Style For Loop

For logic that requires complex increments or conditions, Bash supports C-style syntax.

for (( i=0; i<10; i+=2 )); do
    echo "Even number: $i"
done

II. The Loop Architecture

DATA SETitem_1item_2item_nITERATIONDO ACTION

III. The while Loop: Condition-Based

A while loop runs as long as its condition returns an exit status of 0.

#!/usr/bin/env bash

# Wait for a specific file to appear
while [[ ! -f "ready.txt" ]]; do
    echo "Waiting for process to finish..."
    sleep 2
done
echo "Ready file detected!"

IV. Professional File Processing: while read

When reading a file line-by-line, the combination of while and read is much safer and more memory-efficient than a for loop.

The Role of IFS (Internal Field Separator)

IFS determines how the shell breaks lines into words. By setting it to an empty string, you can preserve leading/trailing whitespace.

#!/usr/bin/env bash

FILE="users.txt"

# -r prevents backslash escapes from being interpreted
while IFS= read -r LINE; do
    echo "Line: $LINE"
done < "$FILE"

V. Interactive Menus with select

The select loop is a specialized tool for creating easy terminal menus.

#!/usr/bin/env bash

PS3="Choose your favorite tool: "
select TOOL in Git Docker Kubernetes Ansible Quit; do
    case $TOOL in
        Quit)
            break
            ;;
        *)
            echo "You chose $TOOL"
            ;;
    esac
done

In the next chapter, we'll learn how to organize our logic into reusable Functions.