Keep your shell scripts from choking on filenames with spaces

Shell Scripting / Bash Tricks

Keep your shell scripts from choking on filenames with spaces

🧩 The Challenge

You finally wrote a decent loop to process backups, only for it to blow up because a single file had a space in the name. I’ve spent way too many nights debugging “file not found” errors that turned out to be shell word splitting.

💡 The Fix

Stop iterating over command output directly and switch to null-terminated streams with a read loop. It saves you from the inevitable mess of filenames with spaces, newlines, or other weird characters.

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

⚙️ Why It Works

By using -print0 with find and the -d ” flag with read, you force the shell to treat the null byte as the delimiter instead of whitespace. Bash suddenly stops trying to break your paths apart at every space it sees.

🚀 Pro-Tip: Always quote your variables like “$file” inside the loop, or you are just asking for trouble all over again.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted