Shell Scripting / Bash Tricks
Stop parsing ls output when you need to loop over files
🧩 The Challenge
Everyone has written that one script where they try to loop over file names by parsing the output of ls, only to have the whole thing blow up the moment a filename contains a space or a newline. It is a classic rookie move that I definitely made for years before learning better.
💡 The Fix
Just stop using ls for logic and start using globbing or the find command with the print0 flag. This keeps your filenames safe, no matter how many weird characters your users decide to shove in there.
find . -maxdepth 1 -type f -name "*.log" -print0 | while IFS= read -r -d '' file; do
echo "Processing $file"
done
⚙️ Why It Works
Setting the internal field separator to null with the -d flag ensures that the shell treats the null character as the delimiter rather than breaking at spaces or newlines. Reading the filename into a variable this way effectively makes your script bulletproof against basically anything that isn’t a directory separator.
🚀 Pro-Tip: Use find’s -exec + flag if you can run the command on all files at once; it is way faster than spawning a subshell for every single file.
Linux Tips & Tricks | © ngelinux.com | 10/19/2026
