Shell Scripting / Bash Tricks
Stop your glob patterns from failing when directories are empty
🧩 The Challenge
Everyone has written a script that tries to loop over files like for file in *.log only to have it blow up because there aren’t any log files today. It is incredibly annoying when your script tries to process the literal string *.log as a filename instead of just moving on with its life.
💡 The Fix
Setting the nullglob option changes how bash treats patterns that don’t match anything. It essentially makes the shell expand those empty globs to nothing rather than the literal pattern string.
shopt -s nullglob
for file in *.log; do
process "$file"
done
shopt -u nullglob
⚙️ Why It Works
Bash defaults to leaving non-matching wildcards alone, which is almost never what you want in an automated pipeline. Flipping this shell option ensures your loops simply don’t run if there is nothing to act on.
🚀 Pro-Tip: Pair this with failglob if you want your script to exit immediately instead of silently skipping empty directories.
Linux Tips & Tricks | © ngelinux.com | 8/7/2026
