Shell Scripting / Bash Tricks
Stop failing your bash scripts because a variable had a space in it
π§© The Challenge
You write a simple script to loop through filenames, but it blows up the second a file with a space in the name shows up. Itβs infuriating when a perfectly fine script fails just because some user decided a filename should have spaces.
π‘ The Fix
Switch your loops to use null-terminated strings instead of the default whitespace-delimited ones. This forces the shell to respect the full path regardless of how many spaces are hidden inside.
find . -maxdepth 1 -name "*.log" -print0 | while IFS= read -r -d '' file; do
echo "Processing $file"
done
βοΈ Why It Works
Setting IFS to an empty string tells read not to trim whitespace, and the -d β flag handles the null delimiter emitted by -print0. Using this combination means you never have to worry about weird characters breaking your logic again.
π Pro-Tip: Always use the -r flag with read unless you actually want backslashes to act as escape characters.
Linux Tips & Tricks | Β© ngelinux.com | 8/22/2026
