How do I loop over find results when filenames have spaces?

November 6, 2026 3 answers
Asked by draftless

I’m trying to find MP3 files in nested directories and process each one. A loop using command substitution splits paths at spaces, so a file like “./bass drum/track.mp3” is treated as two items. What’s a safe way to handle the filenames?

Answers

xenith.4

For a Bash script, use null-delimited output so spaces and other unusual characters in filenames stay intact:

while IFS= read -r -d '' file; do printf '%s\n' "$file"done < <(find . -type f -name '*.mp3' -print0)

Keep the quotes around "$file" when passing it to the command that converts the file. Also quote the pattern in the find command so the shell does not expand it before find receives it.

Reply to this answer
foldedreceipt

If the conversion tool can take one file at a time, let find run it directly:

find . -type f -name '*.mp3' -exec your-converter '{}' \;

The braces are replaced with each full path as a single argument, so spaces are not a problem. Replace the placeholder with the converter command and its options.

Reply to this answer
upside.down

For a simple Bash-only loop, this also works:

shopt -s globstar nullglobfor file in **/*.mp3; do printf '%s\n' "$file"done

That searches below the current directory. The quoted variable matters when you use each path. If you need find's other filtering options, the null-delimited approach is more flexible.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions