Stop getting burned by spaces in filenames when looping
Shell Scripting / Bash Tricks
Stop getting burned by spaces in filenames when looping
🧩 The Challenge
Everyone has written a script that iterates over files, only to have it blow up the second a filename contains a space. It is beyond annoying to have your loops break just because someone decided to name a file “Project Notes.txt”.
💡 The Fix
The trick is to stop iterating over strings and start using null-terminated streams with a while loop. You will save yourself a massive headache by handling file boundaries correctly.
find . -maxdepth 1 -name "*.txt" -print0 | while IFS= read -r -d '' file; do
echo "Processing $file"
done
⚙️ Why It Works
By using -print0 with find and the -d ” flag in read, you are forcing bash to treat the null character as the delimiter rather than whitespace. It is the only reliable way to handle filenames that contain newlines, tabs, or spaces without creating a fragile script.
🚀 Pro-Tip: Always quote your variables like “$file” inside the loop to avoid shell expansion issues.
Linux Tips & Tricks | © ngelinux.com | 12/5/2026
