Site icon New Generation Enterprise Linux

Stop bash word splitting from mangling your filenames with spaces

Shell Scripting / Bash Tricks

Stop bash word splitting from mangling your filenames with spaces

🧩 The Challenge

Dealing with filenames that have spaces in them is a total nightmare because bash assumes a space is a delimiter. I have lost count of the times a script broke because it tried to process a file called “backup 01.tar.gz” as two separate files.

💡 The Fix

Always wrap your variables in double quotes and consider using null-terminated streams for piping files into loops. This forces the shell to treat the variable as a single unit rather than a collection of words.

find . -name "*.txt" -print0 | while IFS= read -r -d '' file; do echo "Processing $file"; done

⚙️ Why It Works

Using -print0 and -d ” tells the system to use a null character instead of a newline to separate items, which is the only way to handle bizarre filenames safely. Since null bytes aren’t allowed in standard filenames, this approach is basically bulletproof.

🚀 Pro-Tip: Stick with the -r flag for read to prevent backslashes from being interpreted as escape characters.

Linux Tips & Tricks | © ngelinux.com | 8/2/2026

0 0 votes
Article Rating
Exit mobile version