Pcornel
Browse topics
Options
Recent
Favorites
Automation · Technical reference

Loops · Bash Automation

Direct answer

Bash loops repeat commands: for item in list, for ((i=0; i<n; i++)), while read -r line for reading files, and until. Quote variables inside loops to handle spaces.

When to use this

Use this when looping over items in Bash.

First 30 seconds

1. Loops: for over globs/arrays, while read for files.

2. Don't parse ls.

3. Handle filenames with spaces.

4. nullglob or existence checks.

5. Avoid subshell variable loss (pipe into while).

Operational verification

items → loop → action

Context & applicabilityCommon mistakes · platform/version boundaries
Platform / version applicability
GNU Bash shell automation
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

PlatformGNU Bash shell automation · Automation implementations are tool and platform specific. Use the adjacent Domain for the technology being automated and this Domain for automation behavior.
Scope / prerequisiteUse this when looping over items in Bash.
What next?3 suggested next steps
Evidence1
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

3 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

Capture the concrete output, symptom, packet, log or counter before changing anything.

Step 1 Verification path Verify boundary

The negative fixture should deliberately exercise risks such as unquoted expansion, globbing, pipeline status loss, subshell scope, set -e misconceptions, signal races, temporary-file leakage and destructive path ambiguity, choosing the cases most relevant to iteration input set, ordering, per-item status, break/continue/failure behavior and safe handling of partial progress. For Bash Automation → Loops, the evidence must connect the control-plane result to the local/remote files, processes, services or APIs changed by the shell workflow and explain any gap between desired, controller-reported and consumer-visible state.

Step 2 Common mistakes Narrow the fault
  • Parsing ls output in loops.
  • for line in $(cat file) splitting on spaces.
Step 3 Where it fails Narrow the fault

Failure analysis for Bash Automation → Loops should follow the path through the components: script/argv/env → Bash expansion/parsing → builtin/external commands → OS/API side effects → exit status/log → target read-back.

Evidence references

Evidence · 1 on this Topic

Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.

observation · 1
Key points
  • Use for item in "${list[@]}" for arrays.
  • Use while IFS= read -r line for files.
  • Never parse ls output in loops.
Key checks
  • while IFS= read -r line; do echo "$line"; done < file — read lines safely
  • for f in /dir/*; do [[ -e $f ]] || continue; done — glob loop
  • mapfile -t arr < file — read into array
ReferenceWhy it matters1 section · depth on demand

In depth

Loops repeat commands for each item — hosts in a file, files in a directory, lines of output. They are the basis of most Bash automation over many targets.

# Each line of a file, safely (handles spaces, no word splitting)
while IFS= read -r host; do
  [[ -z "$host" || "$host" == \#* ]] && continue
  ssh -o ConnectTimeout=5 "$host" uptime || echo "FAILED $host" >&2
done < hosts.txt

# Files, with globbing (no ls parsing)
for f in /srv/backups/*.cfg; do
  [[ -e "$f" ]] || continue
  gzip -9 "$f"
done

# Retry loop
for i in {1..5}; do curl -sf "$URL" && break; sleep $((i*5)); done

Avoid for h in $(cat file) — it splits on spaces and expands wildcards. Quote variables, and use xargs -P or GNU parallel when iterations should run in parallel.

ReferenceImportant terms & boundaries1 section · depth on demand

Mechanics

Bash Automation → Loops is owned at runtime by the Bash process plus invoked Unix utilities and kernel/process environment. The linked authority for bounded mechanics is GNU Bash Reference Manual; documentation support is separate from observed lab/production Evidence.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Technical verification history

Verification history & basis

When and against what this Topic was checked. Later text edits do not count as a new check.

2026-09-14 · vendor docGNU Bash shell automation current

Authoritative/upstream documentation reviewed for bounded claims in Bash Automation > Loops. Documentation verification only; this is not observed lab or production Evidence.

Basis: https://www.gnu.org/software/bash/manual/bash.html · confidence 94%
Depth when you need it

Deep reference

Healthy vs suspicious evidence

Output interpretation

For iteration input set, ordering, per-item status, break/continue/failure behavior and safe handling of partial progress, prefer typed fields and stable IDs over human presentation text.

Confirmation

Confirm action

Continue?