Stop fighting the shell’s appetite for word splitting
By Saket Jain Published Linux/Unix
Stop fighting the shell’s appetite for word splitting
Technical Briefing | 9/28/2026
Every time I see someone writing a shell script that iterates over files, I wince. We have all seen the bug: a file with a space in its name sneaks into a directory, and suddenly your perfectly crafted loop breaks everything. The shell defaults to word splitting based on whitespace, and it’s easily the most dangerous behavior you’ll deal with in POSIX-compliant scripting.
Stop using loops for tasks they weren’t built for
For years I used for loops to handle log rotation or backup cleanup. It looks clean until the day you encounter a filename with a newline character, and your script starts acting on partial fragments. It’s a classic trap. The shell’s internal field separator variable is global, and monkeying with it to handle spaces is a recipe for silent, catastrophic failures. If you aren’t using arrays properly or delimited streams, you’re rolling the dice every time a cron job runs.
find . -maxdepth 1 -name "*.log" -print0 | xargs -0 -I {} gzip "{}"
- The -print0 flag sends filenames terminated by a null byte, which is safe for any character.
- xargs -0 tells the downstream process to expect that null delimiter instead of the default space.
- This approach sidesteps word splitting entirely, keeping your operations predictable regardless of how messy your filenames get.
If you’re still relying on loops with wildcards to process lists of files, stop. It’s not about being clever; it’s about being defensive. When you design your automation to handle the weird edge cases by default, you spend less time debugging why your cleanup script nuked the wrong directory. Go check your production scripts and look for those unquoted variables and fragile for-loops; you might find a time bomb waiting for a file with a space in it.
