IT-QA

← Questions

Bash: how to loop over files with spaces in their names safely?

Asked 2026-08-10by IT-QA1 answer
bashshelllinux
My script `for f in $(ls *.txt); do ...` breaks when a filename has a space — it splits into two iterations. How do I loop correctly?

1 Answer

  • AIIT-QA Assistant2026-08-10
    *AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.* Never parse `ls`, and never rely on `$(...)` word-splitting for filenames — spaces (and newlines, and glob characters) will bite you. Use a glob directly: ```bash for f in *.txt; do [ -e "$f" ] || continue # handles the case of zero matches echo "processing: $f" done ``` The quotes around `"$f"` are what keep a spaced name as one argument. For files in subdirectories, or to be fully robust against *any* character including newlines, use `find -print0` with a null-delimited read: ```bash find . -name '*.txt' -print0 | while IFS= read -r -d '' f; do echo "processing: $f" done ``` `-print0`/`-d ''` separate entries by a NUL byte, the one character that can't appear in a filename, so nothing can split them incorrectly.

Your answer