Stop hunting for the right loop syntax when processing files
Shell Scripting / Bash Tricks
Stop hunting for the right loop syntax when processing files
🧩 The Challenge
Everyone has written those fragile for-loops that break the moment a filename contains a space or a weird newline character. I once spent an entire morning debugging a script that tried to move logs and accidentally nuked half the archive because the variable didn’t handle the spaces correctly.
💡 The Fix
Use the process substitution approach combined with a while-read loop to handle those tricky filenames properly. It makes your scripts bulletproof against even the messiest directory structures.
while IFS= read -r -d '' file; do
echo "Processing $file"
done < <(find . -type f -name "*.log" -print0)
⚙️ Why It Works
By using -print0 with find and -d ” with read, you force the script to treat the null character as the only delimiter, effectively ignoring spaces or weird characters that usually crash standard loops.
🚀 Pro-Tip: Always double-quote your variables like “$file” inside the loop or you’re just asking for trouble again.
Linux Tips & Tricks | © ngelinux.com | 11/26/2026
