Stop fighting with whitespace in your shell loops
Shell Scripting / Bash Tricks
Stop fighting with whitespace in your shell loops
🧩 The Challenge
Dealing with filenames that have spaces in them is a rite of passage that usually ends in a broken script and me wanting to throw my monitor through a window. Every time you pipe an ls output into a for loop, Bash assumes every space is a new item, which makes your script do things you definitely didn’t want it to do.
💡 The Fix
Switching your input to use a null delimiter instead of a newline is the only way to keep your sanity when dealing with messy file lists. It makes the shell treat each entry as a distinct object, so spaces or even newlines in names don’t wreck your logic.
find . -maxdepth 1 -name "*.txt" -print0 | while IFS= read -r -d '' file; do
echo "Processing $file"
done
⚙️ Why It Works
Setting IFS to empty prevents Bash from splitting on tabs and spaces, while the -d ” flag tells the read command to break on the null byte injected by find -print0. It is a bulletproof way to handle filenames that would otherwise choke a standard loop.
🚀 Pro-Tip: Always double-quote your variables inside the loop unless you enjoy debugging edge cases at 3 AM.
Linux Tips & Tricks | © ngelinux.com | 11/21/2026
