Bash Scripting β Iterating Through Lists
Welcome to Chapter 22 β Iterating Through Lists π
Loops are the backbone of automation. In this chapter, youβll master every way Bash lets you walk through collections β arrays, files, command output, glob patterns, and the powerful find/xargs duo.
By the end, youβll handle any list Bash throws at you β safely, efficiently, and without the classic pitfalls that trip up even experienced scripters.
What Youβll Learn
| Lesson | Topic | Key Takeaway |
|---|---|---|
| 01 β Looping Array Elements | Arrays | for, while, indexed, parallel |
| 02 β Looping Directory Listings | Files & Dirs | Globs, find -print0, safe iteration |
| 03 β Looping Command Output | Commands | while read, process substitution, mapfile |
| 04 β Glob Patterns in Scripts | Globs | extglob, nullglob, failglob |
| 05 β find and xargs Pattern | find/xargs | -exec, -print0, parallel xargs |
| 06 β Practice Exercises | Exercises | 5 hands-on challenges |
Why This Chapter Matters
Almost every real-world script needs to process a collection:
- Deploy configs to N servers
- Resize every image in a folder
- Parse every line of a log file
- Act on every pod returned by
kubectl
Getting iteration wrong leads to broken scripts when filenames contain spaces, when lists are empty, or when output changes format. This chapter teaches you the safe patterns.
The Golden Rules of Bash Iteration
#!/usr/bin/env bash
set -euo pipefail
# Rule 1: Quote your expansions
for item in "${array[@]}"; do echo "$item"; done
# Rule 2: Use `while read` for line-by-line command output
some_command | while IFS= read -r line; do echo "$line"; done
# Rule 3: Use find -print0 | xargs -0 for filenames
find /path -name '*.log' -print0 | xargs -0 rm -f
# Rule 4: Enable nullglob when globbing might match nothing
shopt -s nullglob
Quick Decision Guide
Need to iterate over...
β
βββ An array? β Lesson 01
βββ Files in a dir? β Lesson 02
βββ Command output? β Lesson 03
βββ Pattern matches? β Lesson 04
βββ Deep file trees? β Lesson 05
βββ Need practice? β Lesson 06
Prerequisites
Make sure youβre comfortable with:
- Loops β
for,while,until(Chapter 20) - Arrays β indexed & associative (Chapter 21)
- Quoting β double vs single quotes
Letβs Begin
Start with Lesson 01 β Looping Array Elements β
Happy scripting! π