Stop your bash scripts from mangling filenames with spaces

Shell Scripting / Bash Tricks

Stop your bash scripts from mangling filenames with spaces

🧩 The Challenge

You finally wrote that loop to process your log backups, but it blew up the second it hit a filename with a space in it. I’ve spent way too many nights fixing broken file paths that bash decided to split into five different arguments.

💡 The Fix

Use null-terminated streams instead of standard newline-separated lists. It’s the only way to make sure your loops don’t choke on weird characters or spaces in production data.

find . -type f -name "*.log" -print0 | while IFS= read -r -d '' file; do
echo "Processing $file"
done

⚙️ Why It Works

By telling find to output a null byte and having read consume it with the -d ” flag, you turn the file stream into an bulletproof pipe. Bash stops trying to be smart about whitespace and just treats the entire path as one solid block of text.

🚀 Pro-Tip: Always double-quote your variables inside the loop too, or you’re just asking for trouble all over again.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted