Site icon New Generation Enterprise Linux

Stop playing whack-a-mole with shell globbing errors

Shell Scripting / Bash Tricks

Stop playing whack-a-mole with shell globbing errors

đź§© The Challenge

You’ve definitely written a script that tries to loop over files, but then the directory ends up empty and your script treats the literal asterisk as a filename. It’s infuriating when your code tries to act on a file named literally * instead of just skipping the empty directory.

đź’ˇ The Fix

Turn on nullglob so that globs vanish when they don’t match anything instead of expanding to the raw pattern. It saves you from those awkward “file not found” errors on empty directories.

shopt -s nullglob
for file in *.log; do
echo "Processing $file"
done

⚙️ Why It Works

Setting this shell option forces bash to treat non-matching patterns as empty strings rather than leaving the pattern string intact. It makes your loops much cleaner since you aren’t constantly checking if the file actually exists before doing work.

🚀 Pro-Tip: Use shopt -s failglob if you prefer the script to crash immediately rather than running silently on an empty directory.

Linux Tips & Tricks | © ngelinux.com | 10/25/2026

0 0 votes
Article Rating
Exit mobile version