brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: shopt -s nullglob stops a for loop from running on a literal *.log

Shell
~/tips/tip-bash-shopt-nullglob-empty-loop

for f in *.log; do

Makes a bash glob that matches no files disappear, so loops skip instead of failing.

This one has a slightly silly default. When a glob like *.log matches no files, bash doesn’t give you an empty list. It leaves the pattern as it is, so your loop runs once with the text *.log as the “file name”.

cd /tmp/empty-folder
for f in *.log; do
  echo "processing $f"
done
# processing *.log

In a cleanup script that ends with gzip "$f" or mv "$f" archive/, you then get an error about a file that doesn’t exist, or worse, a command that does something with a name you never meant. With nullglob switched on, a pattern that matches nothing is removed, and the loop simply doesn’t run:

shopt -s nullglob
for f in /mnt/user/appdata/myapp/logs/*.log; do
  gzip "$f"
done

It’s also a cheap way to count matches: files=(*.log); echo "${#files[@]}" gives 0 instead of 1 when there are none. If you’d rather have the script stop loudly, shopt -s failglob makes bash print an error and skip the command instead.

The caveat: nullglob affects every command after it, and a command that gets no arguments at all may behave very differently. ls *.log with no matches turns into a plain ls and lists the whole folder. I’d only switch it on in scripts, close to the loop that needs it, and turn it off again with shopt -u nullglob when you’re done.

Further reading: bash(1) manual page

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link