Stop letting your bash scripts break when files have spaces
Shell Scripting / Bash Tricks
Stop letting your bash scripts break when files have spaces
🧩 The Challenge
You’ve written a perfectly good script to loop through filenames, but the second a file has a space in it, the whole thing falls apart and starts treating every word as a separate file. I’ve spent way too many nights debugging broken loops because I forgot that filenames aren’t just strings without spaces.
💡 The Fix
Change the Internal Field Separator to only recognize newlines so the shell stops splitting your variables at every space character. It’s a tiny tweak that saves you from accidental file deletion and absolute insanity.
IFS=$'\n'
for file in $(ls /path/to/files); do
echo "Processing $file"
done
unset IFS
⚙️ Why It Works
Setting the IFS variable tells bash to ignore spaces and tabs as delimiters during word splitting, which forces the loop to respect your actual file boundaries. Keeping this limited to the scope of your loop or resetting it after prevents weird side effects elsewhere in your script.
🚀 Pro-Tip: Use a while read loop combined with find -print0 if you’re dealing with seriously cursed filenames that contain newlines too.
Linux Tips & Tricks | © ngelinux.com | 7/19/2026
