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

Loops in Bash

Updated: May 16, 2026
30 min read

# CHAPTER 6

Loops in Bash

1. Introduction

If a systems administrator needs to create 1,000 new user accounts, they do not write the useradd command 1,000 times in a script. They write the command exactly once and instruct the Bash shell to execute that single line 1,000 times. This concept is called Iteration, and it is the absolute heart of automation. In this chapter, we will master the syntax of loops. We will iterate over lists using the for loop, create infinite background monitors using the while loop, and learn how to forcefully manipulate iteration states using the break and continue control commands.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Construct a for loop to iterate over lists of words, files, or numbers.
  • Construct a while loop to execute code continuously while a condition remains true.
  • Construct an until loop to execute code continuously until a condition becomes true.
  • Utilize the break command to immediately escape a running loop.
  • Utilize the continue command to skip the current iteration and jump to the next one.

3. The for Loop (Iterating over Lists)

The for loop is used when you know exactly how many times you want the code to run. You give it a list of items, and it runs the code once for every item in the list.

Syntax 1: Iterating over words

bash
12345678
#!/bin/bash

# Loop through a predefined list of servers
for SERVER in Web1 Web2 Database1
do
    echo "Connecting to $SERVER..."
    # The code here runs 3 times
done

Syntax 2: Iterating over numbers (C-style) If you want to count from 1 to 5, you can use the traditional programming syntax utilizing double parentheses.

bash
123456
#!/bin/bash

for (( i=1; i<=5; i++ ))
do
    echo "Creating backup number: $i"
done

4. The while Loop (Condition-based)

The while loop is used when you *don't* know how many times the code needs to run. It will run continuously forever, as long as a specific condition remains True.
bash
1234567891011
#!/bin/bash

COUNTER=1

# This loop runs as long as COUNTER is less than or equal to 3
while [ $COUNTER -le 3 ]
do
    echo "Processing batch $COUNTER"
    # MUST INCREMENT THE COUNTER! Otherwise, it is an infinite loop.
    let COUNTER++
done

5. Loop Control: break and continue

Sometimes, you need to intervene in the middle of a loop based on an emergency or an exception.

1. The break Command (The Escape Hatch): If a catastrophic error occurs, break instantly kills the loop and escapes.

bash
12345678910
#!/bin/bash
for (( i=1; i<=10; i++ ))
do
    if [ $i -eq 5 ]; then
        echo "Critical Error at Step 5. Aborting loop!"
        break
    fi
    echo "Processing step $i"
done
# Output will only reach Step 4, then exit.

2. The continue Command (The Skip Button): If you hit a minor error, you don't want to abort the whole loop. You just want to skip that specific item and move to the next one.

bash
12345678910
#!/bin/bash
for SERVER in ServerA ServerB ServerC
do
    if [ "$SERVER" == "ServerB" ]; then
        echo "ServerB is offline. Skipping."
        continue
    fi
    echo "Backing up $SERVER..."
done
# Output: Backs up ServerA, skips B, backs up ServerC.

6. The Infinite Loop (Monitoring)

In DevOps, you often want a script to run permanently in the background, checking the health of a server every 5 seconds. You do this using an intentional infinite while loop.
bash
12345678
#!/bin/bash

while true
do
    echo "Checking server health..."
    # Pause for 5 seconds so you don't melt the CPU
    sleep 5
done

7. Diagrams/Visual Suggestions

*Visual Concept: The Iteration Wheel* Draw a large circle representing the for loop body (do ... done). On the left, draw an input conveyor belt feeding three boxes labeled A, B, C into the top of the circle. Show Box A entering the circle, traveling around, and exiting at the bottom. Then Box B enters. This visualizes that the entire block of code inside do ... done executes completely from top to bottom before the next item in the list is processed.

8. Best Practices

  • Always sleep inside Infinite Loops: If you write a while true loop and forget to include the sleep command, the script will execute the loop millions of times per second. This will instantly consume 100% of your CPU core, locking up the server and potentially requiring a hard reboot.

9. Common Mistakes

  • Forgetting to increment the While Loop counter: If you write a while [ $X -lt 10 ] loop, but you forget to add let X++ at the bottom of the loop, the value of $X will never change. The condition will always remain true, and you will accidentally create an infinite loop that crashes your terminal.

10. Mini Project: Automated File Generator

Let's simulate preparing a workspace for 5 new employees.
  1. 1. nano onboarding.sh
  1. 2. Write the code:
bash
123456789101112131415161718
#!/bin/bash

# Define the list of new hires
NEW_HIRES="Alice Bob Charlie Diana Eve"

echo "Starting automated workspace creation..."

for EMPLOYEE in $NEW_HIRES
do
    echo "Creating directory for $EMPLOYEE..."
    mkdir -p "/tmp/workspace/$EMPLOYEE"
    
    echo "Generating welcome document..."
    echo "Welcome to the company, $EMPLOYEE!" > "/tmp/workspace/$EMPLOYEE/welcome.txt"
done

echo "Onboarding complete. Verifying directories:"
ls -l /tmp/workspace/
  1. 3. chmod +x onboarding.sh
  1. 4. Run it: ./onboarding.sh. You just performed 10 manual administrative actions in 0.1 seconds.

11. Practice Exercises

  1. 1. Contrast the operational use case of a for loop against a while loop. If you need to ping 50 specific IP addresses from a text file, which loop is structurally superior?
  1. 2. Explain the functional difference between the break command and the continue command within the context of iterating through a list of servers.

12. MCQs with Answers

Question 1

A system administrator writes a while true loop to continuously monitor a log file. Which command is absolutely critical to place inside the do...done block to prevent the script from consuming 100% of the CPU's processing power?

Question 2

During a for loop iteration processing 100 files, the script encounters a corrupted file at index 50. The administrator wants the script to log the error, ignore file 50, and immediately proceed to process file 51 without aborting the entire script. Which control command achieves this?

13. Interview Questions

  • Q: A junior engineer writes a while [ $COUNTER -le 10 ] loop, but the script never stops running and eventually crashes the terminal. Explain the mechanical oversight that causes a while loop to become infinite, and how you would fix the code.
  • Q: Explain the C-style for loop syntax for (( i=0; i<10; i++ )). Specifically, break down what the i++ component accomplishes and why it is necessary.
  • Q: You are writing an automation script that loops through an array of databases to perform backups. If the database named 'MasterDB' is encountered, the script should abort the entire backup process immediately to prevent data corruption. Walk me through the control flow logic required to implement this failsafe.

14. FAQs

Q: Can I use wildcards (like *) inside a for loop? A: Yes! This is a massive superpower in Bash. If you write for FILE in *.txt, Bash will automatically look in your current folder, grab every single text file, and loop through them one by one. You can rename 500 files instantly using this method.

15. Summary

In Chapter 6, we unlocked the exponential power of automation through iteration. We mapped predefined lists and numeric sequences into the for loop, transforming a single block of code into a mass-execution engine. We deployed the while loop to evaluate dynamic conditions, utilizing it to construct both counting mechanisms and permanent background monitoring tasks. Finally, we asserted absolute control over our iterative pathways by deploying break to eject from catastrophic failures and continue to gracefully bypass localized errors.

16. Next Chapter Recommendation

Your script can loop through tasks, but as your script grows to 500 lines of code, it will become an unreadable mess. You must learn to modularize your code. Proceed to Chapter 7: Functions in Bash.

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: ·