Loops in Bash
# CHAPTER 6
Loops in Bash
1. Introduction
If a systems administrator needs to create 1,000 new user accounts, they do not write theuseradd 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
forloop to iterate over lists of words, files, or numbers.
-
Construct a
whileloop to execute code continuously while a condition remains true.
-
Construct an
untilloop to execute code continuously until a condition becomes true.
-
Utilize the
breakcommand to immediately escape a running loop.
-
Utilize the
continuecommand 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
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.
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.
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.
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.
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 infinitewhile loop.
7. Diagrams/Visual Suggestions
*Visual Concept: The Iteration Wheel* Draw a large circle representing thefor 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
sleepinside Infinite Loops: If you write awhile trueloop and forget to include thesleepcommand, 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 addlet X++at the bottom of the loop, the value of$Xwill 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.
nano onboarding.sh
- 2. Write the code:
-
3.
chmod +x onboarding.sh
-
4.
Run it:
./onboarding.sh. You just performed 10 manual administrative actions in 0.1 seconds.
11. Practice Exercises
-
1.
Contrast the operational use case of a
forloop against awhileloop. If you need to ping 50 specific IP addresses from a text file, which loop is structurally superior?
-
2.
Explain the functional difference between the
breakcommand and thecontinuecommand within the context of iterating through a list of servers.
12. MCQs with Answers
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?
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 awhileloop to become infinite, and how you would fix the code.
-
Q: Explain the C-style
forloop syntaxfor (( i=0; i<10; i++ )). Specifically, break down what thei++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 thefor 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.