Site icon New Generation Enterprise Linux

Stop failing your bash scripts because a variable had a space in it

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

0 0 votes
Article Rating
Exit mobile version