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 failglob makes bash refuse a wildcard that matches nothing

Bash
~/tips/tip-shell-failglob-unmatched-pattern

shopt -s failglob

Makes bash print an error and skip the command when a wildcard matches no files.

By default, bash hands a wildcard that matches nothing to the command as plain text. With rm or mv in a script, that can be an unpleasant surprise.

The bash manual says that if no file matches and nullglob is off, the word is left unchanged. Turn on failglob and the same situation becomes an error:

shopt -s failglob
rm /tmp/old-*.log

With no matching file, bash prints an error message and does not run the command at all. In bash 5.2 the message looks like bash: line 1: no match: /tmp/old-*.log. Without the option, rm would have received the pattern itself and complained about a file with a star in its name.

A sibling option, nullglob, does the opposite thing: an unmatched pattern expands to nothing and is removed. With failglob you declare that no match is a mistake. With nullglob you declare that it is fine, which is a good fit for a loop over *.log that may have nothing to do.

The caveat is what happens next in a script. In a script file with failglob and an unmatched pattern on line 2, bash 5.2 printed the error, skipped that one command and carried on with line 3, and the script ended with exit status 0. Add set -e before it and the script stops at that line with status 1. So failglob alone prevents the bad command, but only set -e stops the rest from running.

At an interactive prompt a typo in a wildcard now gives you this error and not the usual “no such file”, so I would keep the option for scripts.

Further reading: bash man page (shopt, pathname expansion)

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link