Stop wrestling with glob expansion when paths contain spaces

Shell Scripting / Bash Tricks

Stop wrestling with glob expansion when paths contain spaces

🧩 The Challenge

Everyone knows spaces in filenames are a nightmare, but I still see people breaking their scripts because a simple wildcard loop chokes on a file with a blank in its name. You write a nice script to process your backups and suddenly it’s trying to treat every word in a filename as a separate directory.

💡 The Fix

Use null-terminated strings with find and mapfile or a while-read loop to bypass the shell’s broken-by-default word splitting logic. It saves you from those “file not found” errors that only happen when you aren’t watching.

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

⚙️ Why It Works

Setting the internal field separator to null with the -d flag tells the read command to only break on the null byte character instead of spaces or tabs. This ensures that even the most cursed filenames stay intact during iteration.

🚀 Pro-Tip: Always double-quote your variables, even if you think the path is safe; paranoia is a job requirement in this business.

Linux Tips & Tricks | © ngelinux.com | 11/14/2026

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted