Skip to main content
Shell Scripting – Complete Beginner to Advanced Guide
CHAPTER 06 Intermediate

Loops in Shell Scripting

Updated: May 16, 2026
30 min read

# CHAPTER 6

Loops in Shell Scripting

1. Introduction

If a systems administrator is tasked with updating the operating system on 500 individual servers, manually executing an update script 500 times is inefficient and prone to human error. The core philosophy of DevOps is absolute automation. When you need a single command to run hundreds or thousands of times, you utilize a Loop. A loop instructs the shell interpreter to repeat a block of code until a specific condition is met, or until a list of items is exhausted. In this chapter, we will master the three primary Unix looping architectures: the for loop (for finite lists), the while loop (for condition-based execution), and the until loop (for reverse-condition execution), alongside forceful manipulation using break and continue.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Construct a for loop to iterate systematically over a predefined list of strings or files.
  • Construct a while loop to execute tasks continuously as long as a condition remains True.
  • Construct an until loop to execute tasks continuously until a condition becomes True.
  • Utilize the break command to instantly abort and escape a running loop.
  • Utilize the continue command to skip a localized error and proceed to the next iteration.

3. The for Loop (List Iteration)

The for loop is utilized when you possess a finite, known quantity of items (like a list of 5 server names, or 10 text files) and you want the script to execute the code block exactly once for each item.

Syntax:

sh
12345678
#!/bin/sh

# The loop will run exactly 3 times.
for SERVER in Web1 Web2 DB1
do
    echo "Connecting via SSH to $SERVER..."
    # Imagine SSH connection code here
done

*Note the structure:* The list is provided after in. The variable SERVER dynamically changes to hold the current list item on each pass. The execution block is sandwiched between do and done.

4. The while Loop (Condition-Based)

The while loop is utilized when you *do not* know how many times the code needs to run. It relies on a mathematical or string condition. As long as the condition evaluates to True, the loop runs forever.
sh
1234567891011
#!/bin/sh

COUNTER=1

# Run the loop AS LONG AS the counter is Less Than or Equal To (-le) 3
while [ $COUNTER -le 3 ]
do
    echo "Executing batch process number $COUNTER"
    # CRITICAL: You must increment the counter, or it will run infinitely!
    COUNTER=$(expr $COUNTER + 1)
done

5. The until Loop (Reverse Condition)

The until loop is the exact logical opposite of the while loop. A while loop runs *while* a condition is True. An until loop runs *until* a condition becomes True (meaning it runs while the condition is False).
sh
1234567891011121314
#!/bin/sh

# Imagine a script waiting for a service to crash
STATUS="running"

# The loop runs AS LONG AS STATUS is NOT "crashed"
until [ "$STATUS" = "crashed" ]
do
    echo "Service is operating normally..."
    # A real script would check the service here. 
    # We will manually trigger the break for this example.
    STATUS="crashed"
done
echo "ALERT: Service has crashed. Loop exited."

6. Loop Control (break and continue)

Automation scripts frequently encounter anomalies. You need manual overrides to control the loop's execution flow.

1. The break Statement (The Escape Hatch): If a catastrophic failure occurs during a loop, break instantly kills the entire loop and drops execution to the code beneath the done statement.

sh
123456789
#!/bin/sh
for FILE in file1 file2 file3
do
    if [ "$FILE" = "file2" ]; then
        echo "Corrupt file detected! Aborting entire process."
        break
    fi
    echo "Processing $FILE..."
done

2. The continue Statement (The Skip Button): If a minor, non-fatal error occurs, you don't want to stop the whole script. continue skips the rest of the current pass and instantly jumps to the next item in the list.

sh
12345678910
#!/bin/sh
for USER in Alice Bob Charlie
do
    if [ "$USER" = "Bob" ]; then
        echo "Bob's account is locked. Skipping."
        continue
    fi
    echo "Updating password for $USER..."
done
# Output: Updates Alice, skips Bob, updates Charlie.

7. Diagrams/Visual Suggestions

*Visual Concept: The Iteration Conveyor Belt* Draw a circular track representing the while loop. At the top of the circle is a gateway labeled: [ $COUNT -le 5 ]. Inside the circle is a box labeled: Execute Code. At the bottom of the circle is an arrow pointing back up to the top gateway. Beside the bottom arrow, place a bright red sign: WARNING: Must increment COUNT here!. This visualizes the infinite circular nature of the while loop and explicitly highlights the necessity of the incrementing mathematical expression to break the cycle.

8. Best Practices

  • Use for loops for Directory Parsing: You can utilize wildcards in a for loop to automatically generate a list of files in a directory. For example, for FILE in *.txt will instantly locate every .txt file in the current working directory and loop through them one by one.

9. Common Mistakes

  • The Infinite While Loop: The most common and devastating error in shell scripting is writing a while [ $X -lt 10 ] loop, but forgetting to write X=$(expr $X + 1) inside the loop block. If the variable never increases, the condition never evaluates to False. The script will consume 100% of the CPU core indefinitely until the administrator forcibly kills the process.

10. Mini Project: Automated File Provisioning

Let's build a script that uses a for loop to generate bulk directories, mimicking a workspace setup for new developer environments.
  1. 1. nano provision.sh
  1. 2. Write the code:
sh
123456789101112131415161718
#!/bin/sh

# The list of developer environments to create
DEVS="frontend backend database devops"

echo "Initiating bulk workspace provisioning..."

for ENV in $DEVS
do
    echo "Provisioning directory for $ENV team..."
    mkdir -p "/tmp/workspaces/$ENV"
    
    # Create a default configuration file inside the new folder
    touch "/tmp/workspaces/$ENV/config.ini"
done

echo "Provisioning complete. Verifying structure:"
ls -l /tmp/workspaces/
  1. 3. chmod +x provision.sh and run it. You just performed 8 administrative file-system commands dynamically using only 4 lines of core logic.

11. Practice Exercises

  1. 1. Contrast the structural design of a for loop against a while loop. In a scenario where you must parse exactly 50 distinct IP addresses listed in a text file, which looping architecture is structurally superior?
  1. 2. Explain the functional difference between the break command and the continue command. What distinct operational outcomes occur when they are triggered?

12. MCQs with Answers

Question 1

When engineering a while loop designed to execute 10 times, what catastrophic outcome occurs if the developer forgets to include an arithmetic increment expression (e.g., COUNT=$(expr $COUNT + 1)) inside the do block?

Question 2

During a massive for loop processing 1,000 files, the script encounters a corrupted file at index 500. The administrator wants the script to log the error, ignore the corrupted file, and immediately proceed to process file 501. Which control statement accomplishes this?

13. Interview Questions

  • Q: A junior administrator writes a script to wait for a database server to come online. They use a while loop that pings the server repeatedly. Explain why it is an absolute architectural necessity to include the sleep command inside this specific looping structure.
  • Q: Explain the logical inversion between the while loop and the until loop. Walk me through a specific administrative monitoring scenario where using until is more readable and intuitive than using while.
  • Q: You are utilizing a for loop to read a list of file names from a variable (FILES="doc1 doc2 doc3"). A user accidentally creates a file named "my document". Walk me through the exact "Word Splitting" error that will occur when the loop attempts to process that specific filename.

14. FAQs

Q: Can I put an if statement inside a loop? A: Absolutely. This is the foundation of complex automation. You use the loop to process 500 items, and you use an if statement *inside* the loop to inspect each individual item as it passes through, deciding whether to modify it or skip it.

15. Summary

In Chapter 6, we unlocked the exponential multiplier effect of the shell interpreter. We transitioned from linear, single-execution scripts into cyclical automation engines. We deployed the for loop to systematically process finite lists and parse directory structures. We constructed dynamic, condition-dependent execution cycles utilizing the while and until architectures. Finally, we established absolute administrative control over our cyclical pathways by injecting the break and continue override commands, ensuring our scripts remain resilient and responsive to catastrophic errors and minor anomalies alike.

16. Next Chapter Recommendation

Your scripts can now execute thousands of lines of code, but writing thousands of lines of code is inefficient and violates the DRY (Don't Repeat Yourself) principle. We must learn to modularize our code blocks. Proceed to Chapter 7: Functions in Shell Scripts.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·