Pcornel
Automation · Bash Automation

Loops

Cheat sheet · https://pcornel.dk/topic.php?topic=5280

Back to the Topic

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.

Remember

  • Use for item in "${list[@]}" for arrays.
  • Use while IFS= read -r line for files.
  • Never parse ls output in loops.

First 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

Verify in this order

items → loop → action

Where it usually breaks

Input/desired state → request accepted → job/task terminal status → target object read-back → effective runtime state → original workload → regression/rollback readiness.

Read-only verification commands unless stated otherwise. Confirm syntax for your platform and release. Full reference: https://pcornel.dk/topic.php?topic=5280

Confirmation

Confirm action

Continue?