Loops in Shell Scripting
# 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: thefor 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
forloop to iterate systematically over a predefined list of strings or files.
-
Construct a
whileloop to execute tasks continuously as long as a condition remains True.
-
Construct an
untilloop to execute tasks continuously until a condition becomes True.
-
Utilize the
breakcommand to instantly abort and escape a running loop.
-
Utilize the
continuecommand 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:
*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.
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).
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.
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.
7. Diagrams/Visual Suggestions
*Visual Concept: The Iteration Conveyor Belt* Draw a circular track representing thewhile 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
forloops for Directory Parsing: You can utilize wildcards in aforloop to automatically generate a list of files in a directory. For example,for FILE in *.txtwill instantly locate every.txtfile 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 writeX=$(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 afor loop to generate bulk directories, mimicking a workspace setup for new developer environments.
-
1.
nano provision.sh
- 2. Write the code:
-
3.
chmod +x provision.shand run it. You just performed 8 administrative file-system commands dynamically using only 4 lines of core logic.
11. Practice Exercises
-
1.
Contrast the structural design of a
forloop against awhileloop. In a scenario where you must parse exactly 50 distinct IP addresses listed in a text file, which looping architecture is structurally superior?
-
2.
Explain the functional difference between the
breakcommand and thecontinuecommand. What distinct operational outcomes occur when they are triggered?
12. MCQs with Answers
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?
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
whileloop that pings the server repeatedly. Explain why it is an absolute architectural necessity to include thesleepcommand inside this specific looping structure.
-
Q: Explain the logical inversion between the
whileloop and theuntilloop. Walk me through a specific administrative monitoring scenario where usinguntilis more readable and intuitive than usingwhile.
-
Q: You are utilizing a
forloop 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 anif 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 thefor 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.