Site icon New Generation Enterprise Linux

Stop your shell scripts from choking on filenames with spaces

Shell Scripting & Automation

Stop your shell scripts from choking on filenames with spaces

Technical Briefing | 7/25/2026

You spend hours writing a cleanup script, test it on a handful of local files, and deploy it to production. Everything runs fine until a user creates a file with a space in the name. Suddenly, your loop is treating the first half of the filename as one file and the second half as another. It happens to everyone at least once, and it is infuriating to debug when you are staring at a logs folder full of half-deleted artifacts.

The loop trap you keep falling into

Most of us grow up writing for loops like for file in $(ls). It is intuitive, it looks clean, and it fails the moment you have a filename containing a space, a tab, or a newline. The shell is splitting on whitespace because that is the default behavior of the internal field separator. If you want your scripts to be bulletproof, you have to stop using output command substitution for file lists.

find . -maxdepth 1 -type f -print0 | while IFS= read -r -d '' file; do echo processing "$file"; done
  • The -print0 argument terminates file paths with a null byte rather than a newline
  • Setting IFS to empty prevents the shell from trimming whitespace at the start and end of names
  • The -r flag ensures read treats backslashes as literal characters instead of escape sequences
  • Wrapping your variable in double quotes is mandatory, not optional, if you want to prevent word splitting

This pattern might look a bit uglier than a basic loop, but it is portable and safe. The next time you find yourself tempted by the simplicity of a wildcard glob or a backtick execution, remember that edge cases are exactly where production scripts go to die. Stop the madness now and force yourself to use null-delimited inputs for everything you touch.

Linux Admin Automation  |  © www.ngelinux.com  |  7/25/2026
0 0 votes
Article Rating
Exit mobile version