Stop getting burnt by shell variable whitespace issues
Technical Briefing | 9/6/2026
You spend half your time writing scripts that move files or process config lines, then one day a filename shows up with a space in it and your entire pipeline shatters. I have seen perfectly good automated backups dump half their contents into the wrong directory because someone named a folder with a space and the script was not prepared for it. It is a classic trap.
The trap is almost always word splitting
The shell is helpful, maybe too helpful. When you reference a variable like $my_var without quotes, the shell performs word splitting and globbing on the expansion. This means a single string containing spaces suddenly becomes multiple arguments passed to your command. If you are running an rm or an mv, this is usually where the site goes down.
find . -maxdepth 1 -type f -print0 | xargs -0 ls -lh
- Always quote your variables to prevent word splitting
- Use null delimiters whenever your tools support them
- Avoid parsing ls output because it will fail on exotic characters
- Use the array syntax if you need to handle lists of paths reliably
If you are iterating over files, do not use for file in $(ls). It is fragile and breaks the second a filename has a newline. Just use a glob pattern or find. If you have to handle dynamic lists, arrays are your best friend. They keep items grouped together and save you from the mental fatigue of escaping characters manually.
Next time you are writing a loop, stop and ask yourself if you really need the shell to split those strings. If the answer is no, keep it quoted. It is a small habit, but it will save you from that 3 AM incident response call when a user finally creates a file named with a trailing space.
