The Power of Repetition: For and While Loops
·TechSoftware Development

The Power of Repetition: For and While Loops

Master the art of high-volume automation. Learn to process hundreds of files in seconds using 'For' loops, and create persistent background tasks using 'While' loops. Discover and master the 'Until' logic.

Loops: Automating at Scale

Imagine you have a folder with 1,000 .log files and you need to rename all of them to .old. You could type the mv command 1,000 times, but that would take hours. In Bash, you can do it in two lines.

Loops allowed you to apply a command (or a block of commands) to a "List" of things. Whether it's a list of filenames, a list of users, or a range of numbers, loops are the engine of high-volume administration.

In this lesson, we will master the for, while, and until loops.


1. The 'For' Loop: Iterating Over Lists

The for loop is used when you have a pre-defined list of items.

for item in item1 item2 item3; do
    echo "Processing $item"
done

The Most Common Case: Iterating Over Files

Bash "Wildcards" are perfect for for-loops.

# Mass rename .txt to .md
for file in *.txt; do
    mv "$file" "${file%.txt}.md"
    echo "Renamed $file"
done

Iterating Over Numbers:

# Print numbers 1 to 10
for i in {1..10}; do
    echo "Count: $i"
done

2. The 'While' Loop: Running until a Condition Changes

The while loop runs as long as a condition is TRUE. It is excellent for "Monitors" or background tasks.

#!/bin/bash
COUNT=1
while [ $COUNT -le 5 ]; do
    echo "Attempt $COUNT"
    ((COUNT++))
    sleep 1
done

The "Infinite" Loop (Polling):

while true; do
   # Check if website is up
   STATUS=$(curl -o /dev/null -s -w "%{http_code}" https://google.com)
   echo "Status: $STATUS"
   sleep 60
done

3. The 'Until' Loop: Reverse Logic

The until loop is the opposite of while. It runs as long as a condition is FALSE.

# Wait for a file to be created by another process
until [ -f "/tmp/ready.txt" ]; do
    echo "Waiting for process to finish..."
    sleep 2
done
echo "Ready file detected! Proceeding..."

4. Break and Continue

Sometimes you want to exit a loop early.

  • break: Stop the loop immediately and move to the next part of the script.
  • continue: Skip the current iteration and jump back to the top of the loop.

5. Practical: The "Mass Image Converter"

Suppose you have a folder of .png files and you want to convert them all to .jpg.

#!/bin/bash

# Ensure we are in a directory with images
for img in *.png; do
    if [ -f "$img" ]; then
        echo "Converting $img..."
        # We assume the 'convert' tool from ImageMagick is installed
        convert "$img" "${img%.png}.jpg"
    else
        echo "No PNG files found."
        break
    fi
done

6. Example: A Batch Job Simulator (Python)

If you are a developer, you might want to simulate a long loop to test how your system handles stress. Here is a Python script that generates a "Batch Job" of shell commands and runs them in a loop.

import subprocess
import time

def run_simulated_batch(count=10):
    """
    Simulates a loop of shell tasks.
    """
    print(f"Starting batch of {count} tasks...")
    print("-" * 30)
    
    for i in range(1, count + 1):
        # Simulate a shell command like 'echo Task X; sleep 1'
        cmd = ["echo", f"Processing Task {i}/{count}..."]
        subprocess.run(cmd)
        
        # Simulate work time
        time.sleep(0.5)
        
    print("\n[SUCCESS] Batch complete.")

if __name__ == "__main__":
    run_simulated_batch(5)

7. Professional Tip: Use 'while read' for Files

If you want to process a text file line-by-line (like a CSV or a list of users), don't use a for loop (it will break on spaces!). Use the while read pattern.

# Read every line of 'users.txt' safely
while read -r line; do
    echo "Creating user: $line"
done < users.txt

8. Summary

Loops turn a simple script into a high-powered engine.

  • for is for Lists and Files.
  • while is for Conditions and Monitors.
  • until is for Waiting for an event.
  • break allows for an emergency exit.
  • Always use while read when processing files with spaces in them.

In the next lesson, we will organize our code using Functions and Scope.

Quiz Questions

  1. How do you loop through all files in the current folder that start with the letter "A"?
  2. What is the difference between break and continue?
  3. Why is while true often used for system monitoring scripts?

Continue to Lesson 5: Functions and Scope—Designing Professional Shell Scripts.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn