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
