Stop letting your bash scripts lie to you about empty arrays

Shell Scripting / Bash Tricks

Stop letting your bash scripts lie to you about empty arrays

🧩 The Challenge

You write a script to process a list of files, but if the glob doesn’t match anything, the script treats the literal string as a filename and tries to process it. I’ve wasted a whole afternoon debugging a cron job because it tried to ‘rm’ a literal asterisk instead of just doing nothing.

💡 The Fix

Flip the nullglob shell option on at the start of your script so Bash treats non-matching patterns as empty lists instead of leaving the pattern string intact. It saves you from writing those redundant if-checks that only exist to clean up shell behavior.

shopt -s nullglob
files=(/var/log/app/*.log)
for f in "${files[@]}"; do
# Your logic here
done

⚙️ Why It Works

Setting this option changes how the shell expands wildcards when they don’t find a match. Instead of passing the literal text to your script, it results in an empty array, which is usually exactly what you wanted in the first place.

🚀 Pro-Tip: Use ‘shopt -s failglob’ if you prefer your script to explode immediately when a pattern fails to match.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted