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: *.@(jpg|png) matches several extensions in one shell glob

Shell
~/tips/tip-shell-extglob-at-alternatives

shopt -s extglob

Match a list of extensions without the empty results that braces leave.

*.{jpg,png,webp} looks like a glob for three extensions, but braces are expanded first into three separate globs. Any type you do not have stays as a literal *.webp in the command.

With extglob on, @(a|b|c) matches exactly one of the alternatives, inside a single glob:

shopt -s extglob
ls *.@(jpg|jpeg|png)

This gives only the files that exist. Compare it in a folder with one PNG:

echo *.{jpg,png,webp}
# *.jpg c.png *.webp
echo *.@(jpg|png|webp)
# c.png

That leftover *.webp is what makes cp *.{jpg,png,webp} dest/ fail with a confusing No such file error.

Set shopt -s extglob on its own line, before the line that uses the pattern. Bash reads a whole line before it runs any of it, so putting both on one line gives a syntax error near (, which I find an annoying trap. On many distributions the bash-completion package switches extglob on in interactive shells, but scripts start without it. The other operators work the same way: +(...) for one or more, ?(...) for zero or one.

Further reading: Bash manual: Pattern Matching

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