Site icon New Generation Enterprise Linux

Stop your bash loops from choking on filenames with spaces

Shell Scripting / Bash Tricks

Stop your bash loops from choking on filenames with spaces

đź§© The Challenge

You have probably written a simple for loop to iterate over files, only to have it blow up because some genius decided to name a file “Project Data Final 01.txt”. It’s the kind of thing that makes you want to throw your keyboard out the window when a script fails mid-run.

đź’ˇ The Fix

Don’t just iterate over the output of ls. Switch to using a while read loop combined with a null-terminated find command to keep your filenames intact regardless of the weird characters inside them.

find . -maxdepth 1 -name "*.txt" -print0 | while IFS= read -r -d '' file; do
echo "Processing $file"
done

⚙️ Why It Works

Using -print0 tells find to separate results with a null character rather than a newline, which is the only character that can’t actually appear in a Linux filename. The IFS= and -d ” flags in the read command ensure bash respects that null delimiter and doesn’t trim leading or trailing whitespace.

🚀 Pro-Tip: Always double-quote your variables inside the loop or you’re just begging for the shell to word-split your path anyway.

Linux Tips & Tricks | © ngelinux.com | 8/5/2026

0 0 votes
Article Rating
Exit mobile version