Stop letting your bash loops blow up on globbing errors
Shell Scripting / Bash Tricks
Stop letting your bash loops blow up on globbing errors
🧩 The Challenge
Everyone has written a loop like for i in *.txt; do something; done only to have it blow up because there aren’t any text files in the directory. You end up with your script trying to process the literal string *.txt instead of just skipping it.
💡 The Fix
Use a simple bash shell option to make the glob expand to nothing if no matches are found, which cleanly terminates the loop before it even starts.
shopt -s nullglob
for file in *.txt; do
echo "Processing $file"
done
⚙️ Why It Works
By enabling nullglob, bash stops being helpful by passing the unexpanded pattern as a filename. It simply wipes the argument list clean when nothing matches the wildcard, saving you from writing extra if statements to check for file existence.
🚀 Pro-Tip: Add this to your ~/.bashrc if you want your interactive shell to behave the same way; it makes wildcard tab-completion much less annoying.
Linux Tips & Tricks | © ngelinux.com | 9/1/2026
