Loops — Automating Repetitive Tasks in Bash Scripts¶
Loops allow Bash scripts to execute a block of code repeatedly until a specified condition is met or a collection of items has been processed. Instead of writing the same commands multiple times, loops enable automation with fewer lines of code, making scripts more efficient, scalable, and maintainable. Loops are extensively used in Linux administration, DevOps, cloud automation, infrastructure management, monitoring, and deployment pipelines.
Learning Path¶
Course Progress
What You'll Learn¶
After completing this lesson, you'll be able to:
- Understand loops
- Use
forloops - Use
whileloops - Use
untilloops - Iterate through files and directories
- Read files line by line
- Control loops using
breakandcontinue - Apply loops in production automation
Prerequisites¶
Complete:
- Modules 1–9
- Module 10 Lessons 1–2
Why Learn Loops?¶
Imagine backing up multiple directories.
Without loops:
Using a loop:
The script becomes shorter, reusable, and easier to maintain.
What is a Loop?¶
A loop repeatedly executes a block of commands.
Example:
Types of Loops¶
Bash supports:
forwhileuntil
Each is useful in different scenarios.
for Loop¶
The for loop is used when iterating over a known list of items.
Syntax:
Example:
Output:
Numeric for Loop¶
Using brace expansion:
Output:
C-Style for Loop¶
Loop Through Files¶
Loop Through Directories¶
while Loop¶
A while loop runs as long as the condition is true.
Syntax:
Example:
Reading a File Line by Line¶
This technique is widely used for processing configuration files and logs.
until Loop¶
An until loop executes until a condition becomes true.
Syntax:
Example:
break Statement¶
break exits a loop immediately.
Example:
Output:
continue Statement¶
continue skips the current iteration.
Example:
Output:
Nested Loops¶
Loops can be placed inside other loops.
Infinite Loop¶
Stop using:
Common Commands¶
Simple loop.
While loop.
Until loop.
Exit loop.
Skip iteration.
Real Production Examples¶
Backup multiple directories.
Check multiple servers.
Process log file.
Production Perspective¶
Loops are widely used in:
- Backup automation
- Log processing
- CI/CD pipelines
- Infrastructure provisioning
- Cloud automation
- Kubernetes administration
- Server monitoring
- Configuration management
Most production Bash scripts rely on loops to automate repetitive tasks.
Hands-on Lab¶
Task 1¶
Print numbers.
Task 2¶
Print file names.
Task 3¶
Create five directories.
Task 4¶
Use a while loop.
Task 5¶
Read a file.
Task 6¶
Use break.
Task 7¶
Use continue.
Task 8¶
Create an infinite loop.
Stop it with:
Command Deep Dive¶
| Command | Purpose | Production Example |
|---|---|---|
for | Iterate over items | File processing |
while | Repeat while condition is true | Monitoring |
until | Repeat until condition becomes true | Retry logic |
break | Exit loop | Error handling |
continue | Skip current iteration | Filtering |
read | Read input line by line | Log processing |
Common Loop Mistakes¶
| Mistake | Solution |
|---|---|
Missing done | Close every loop |
| Infinite loop | Update loop condition |
| Forgetting to increment variables | Modify loop counter |
| Using the wrong loop type | Choose the appropriate loop |
| Not quoting filenames | Quote variables containing paths |
Production Troubleshooting Scenario¶
Scenario
A monitoring script should check multiple servers.
Without loops:
Using a loop:
for HOST in server1 server2 server3
do
if ping -c1 "$HOST" >/dev/null
then
echo "$HOST is reachable"
else
echo "$HOST is down"
fi
done
The script is easier to maintain and can scale to hundreds of servers.
Best Practices¶
- Choose the appropriate loop type.
- Keep loop bodies simple.
- Avoid unnecessary nested loops.
- Quote filenames and variables.
- Use
breakandcontinueto improve readability. - Test loops with small datasets before running them in production.
Common Mistakes¶
❌ Forgetting the closing done.
✅ Remember to the closing done.
❌ Creating unintended infinite loops.
✅ Avoid this mistake: creating unintended infinite loops.
❌ Not updating loop variables.
✅ Always updating loop variables.
❌ Using for when while is more appropriate.
✅ Avoid using for when while is more appropriate when a safer approach exists.
❌ Processing filenames without quoting variables.
✅ Avoid this mistake: processing filenames without quoting variables.
Interview Questions¶
Beginner¶
- What is a loop?
- What are the three loop types in Bash?
- What is the purpose of a
forloop? - What is the purpose of a
whileloop?
Intermediate¶
- What is the difference between
whileanduntil? - What does
breakdo? - What does
continuedo? - How do you read a file line by line in Bash?
Architect Level¶
- How would you automate server health checks using loops?
- How would you process thousands of log files efficiently?
- How can poorly designed loops affect production systems?
Summary¶
In this lesson, you learned:
forloopswhileloopsuntilloops- Nested loops
- Reading files line by line
breakcontinue- Production automation techniques
Loops are one of the most powerful features of Bash scripting. They eliminate repetitive code, simplify automation, and enable scripts to process files, users, servers, and system resources efficiently. Mastering loops is essential for writing scalable and production-ready Bash scripts.
Key Takeaways¶
- Loops automate repetitive tasks.
- Use
forloops when the number of iterations is known. - Use
whileloops when execution depends on a condition. - Use
untilloops to repeat until a condition becomes true. - Use
breakto exit loops andcontinueto skip iterations. - Keep loops simple, efficient, and easy to read.
What's Next?¶
Functions — Writing Reusable Code in Bash Scripts
You'll explore:
- Creating functions
- Function parameters
- Returning values
- Variable scope
- Reusable code
- Organizing large scripts
- Production scripting best practices
By the end of the lesson, you'll be able to build modular, reusable Bash scripts using functions, making your automation easier to maintain and scale.