Safe Filename Loops With Bash Arrays

Collect names in an array and iterate with quoted expansion.

macOSbashshellscriptingLow risk
Use files=(*.md) then for f in "${files[@]}"; do ...; done to handle names with spaces.

01Command

Command
$ files=(*.md); for f in "${files[@]}"; do echo "$f"; done

02What it does

The pattern for f in *.md breaks on filenames containing spaces, while an array preserves each element exactly. This is the reliable way to process many files in scripts, and it is a common source of automation bugs that a GUI never has to face.

03Risk

RiskLow risk
RequirementsmacOS default zsh/bash (bash 3.2+; some features need bash 4+ via Homebrew)
CompatibilitymacOS with bash 3.2+ (GNU bash 4+ via Homebrew for advanced features)
!Warning: Always quote "${array[@]}"; unquoted expansion re-splits elements on whitespace.

04Undo

✓No undo needed — this command does not change persistent state.

05Sources

Last verified: 2026-10-13 · Category: Developer