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: with extglob, !(*.log) matches everything except your log files

Shell
~/tips/tip-shell-extglob-not-pattern

shopt -s extglob

Lists or selects every file except the ones matching a pattern, using Bash extended globs.

Plain globs can only say what you want. Saying what you do not want normally means a loop or a grep -v. Extended globs fix that.

Turn on extglob and Bash understands patterns like !(pattern), ?(pattern), +(pattern) and @(a|b). The first one is the one I reach for.

$ shopt -s extglob
$ ls !(*.log)
$ rm -- !(keep.txt|keep.md)

The second line lists everything that is not a .log file. The third deletes everything except two files, which is shorter than any alternative I can think of. Do an ls with the same pattern first. That is not paranoia, rm has no undo.

Caveat: you must run shopt -s extglob on a line before the line that uses the pattern. Bash parses a whole line before executing it, so putting both on one line, or in a bash -c string, gives a syntax error. In scripts that is rarely a problem, since the shopt sits at the top. Zsh has its own syntax for this, enabled with setopt extendedglob.

Inside a script this is also a tidy way to say “all arguments except these” in a for loop, without a nested if that skips the files you did not want.

Further reading: Bash manual: Pattern Matching, Bash manual: The Shopt Builtin, On this site: shopt -s globstar lets ** match files in every subfolder, On this site: diff <(cmd1) <(cmd2) compares output without temp files

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