Site icon New Generation Enterprise Linux

Stop bash from splitting your filenames with spaces

Shell Scripting / Bash Tricks

Stop bash from splitting your filenames with spaces

🧩 The Challenge

You finally write that loop to process log files, but then a file with a space in the name shows up and your script loses its mind. It’s infuriating when a simple loop tries to open ‘My’ and ‘Log.txt’ as two separate files instead of one.

💡 The Fix

Change the way bash splits input by setting the Internal Field Separator to handle only newlines. This ensures your loop respects the actual filename boundaries instead of breaking at every space.

IFS=$'\n'
for file in $(find /var/log/myapp -name "*.log"); do
cat "$file"
done
unset IFS

⚙️ Why It Works

Setting IFS to just the newline character tells the shell to ignore spaces and tabs when splitting the output of your command substitution. Without this, the shell assumes every space is a delimiter, which is rarely what you want when handling real-world file paths.

🚀 Pro-Tip: Always wrap your variables in double quotes inside the loop, just in case you forget to unset IFS later.

Linux Tips & Tricks | © ngelinux.com | 7/22/2026

0 0 votes
Article Rating
Exit mobile version