Globbing, extglob and Pattern Matching

Globbing, extglob and Pattern Matching in Bash: --- Walk into a packing shed at harvest time and you will find the grading machine: a long belt that carries…


The Analogy: The Fruit-Grading Machine's Sizing Rings

Walk into a packing shed at harvest time and you will find the grading machine: a long belt that carries apples past a series of holes cut into a steel plate, each hole a different size. An apple rolls along until it reaches a hole it fits through, and drops into the crate below. The small holes come first, then larger ones, so each apple falls at the first opening wide enough to pass it. The plate of holes is a set of patterns, and each apple is tested against them in turn. This is exactly what a shell glob does: a pattern is a shaped opening, and every filename in the directory is an apple rolled past it to see whether it fits.

The shapes of the openings vary in a way that maps cleanly onto glob syntax. A perfectly round hole of an exact diameter passes only apples of one size -- that is a literal filename, matching just itself. A very wide hole passes anything at all -- that is the * wildcard, which matches any run of characters. A hole with a single narrow slot passes apples with one specific bump -- that is ?, which matches exactly one character. And a hole cut to accept a range of diameters, say anything between two marked sizes, is the bracket expression [a-c], which matches one character from a named set or range.

The grader also has settings that change the machine's behaviour rather than any single hole. If the operator flips the switch that says "when nothing fits a hole, send the belt around empty rather than jamming a dummy apple into the crate", that is nullglob: a pattern that matches nothing expands to nothing instead of staying as literal text. Another switch says "also grade the bruised fruit you normally leave in the bin", which is dotglob: include the hidden dotfiles that globs skip by default. And the deluxe model has compound openings -- a hole that accepts this size or that size, or everything except one size -- which is extglob, the extended patterns like @(...) and !(...).

The failure mode is a hole cut too generously. If a ring meant to pass only medium apples has worn wide over a season, undersized fruit slips through and ends up in the wrong crate, and nobody notices until a customer complains. A glob that is broader than intended does the same: * where you meant *.txt sweeps up files you never meant to touch, and because the shell hands the expanded list straight to the command, a careless rm * deletes far more than the author pictured. And Bash has one genuinely surprising default -- when a pattern matches nothing, it is left unchanged as literal text and passed along as if it were a filename, which is the machine dropping the sizing ring itself into the crate. Understanding these behaviours before writing a glob into a destructive command is the difference between a tidy run and a very bad afternoon.


Syntax or Core Structure

The three core glob metacharacters are * (any run of characters, including none), ? (exactly one character), and [...] (one character from a set or range, or the complement with a leading !). The shell expands these against filenames in the current directory before the command runs. This script runs each pattern against a fixed set of files so the matches are reproducible; LC_ALL=C pins the sort order to byte order.

#!/usr/bin/env bash
LC_ALL=C
# directory contains: alpha.txt beta.txt gamma.txt
#   app1.log app2.log app10.log
#   data1.csv data2.csv data9.csv  .hidden.txt
echo "-- *.txt --";        printf '%s\n' *.txt
echo "-- app?.log --";     printf '%s\n' app?.log
echo "-- [ab]*.txt --";    printf '%s\n' [ab]*.txt
echo "-- data[0-9].csv --"; printf '%s\n' data[0-9].csv
echo "-- [!a]*.txt --";    printf '%s\n' [!a]*.txt

Output:

-- *.txt --
alpha.txt
beta.txt
gamma.txt
-- app?.log --
app1.log
app2.log
-- [ab]*.txt --
alpha.txt
beta.txt
-- data[0-9].csv --
data1.csv
data2.csv
data9.csv
-- [!a]*.txt --
beta.txt
gamma.txt

Read each result against its pattern. *.txt matches the three text files but not .hidden.txt, because a leading dot is not matched by * unless dotglob is set -- a default that protects hidden files from casual globs. app?.log matches app1 and app2 but not app10, because ? is exactly one character and 10 is two. [ab]*.txt requires the first character to be a or b, so gamma.txt is excluded. data[0-9].csv uses a range for a single digit. Finally [!a]*.txt inverts the set: the first character must not be a, so alpha.txt drops out and beta.txt and gamma.txt remain. The shell sorts every expansion, which under LC_ALL=C is plain byte order.


Technical Depth: Options, the Empty-Match Default, and extglob

The shopt switches that change globbing

Globbing has several behaviours controlled by shopt, the shell-option command. These are the machine settings from the analogy: they change how every pattern behaves, not what any single pattern matches.

OptionDefaultWhen setTypical use
nullgloboffunmatched pattern expands to nothingsafe loops over maybe-empty sets
dotgloboffpatterns also match leading-dot namesincluding hidden files deliberately
nocasegloboffmatching ignores casematching JPG and jpg together
failgloboffunmatched pattern is an errorcatching typos in required inputs
extgloboffenables the @() !() +() patternscompound matching

The unquoted empty-match surprise

Bash's default when a pattern matches nothing is jarring the first time you see it: the pattern is left in place as literal text and passed to the command unchanged. nullglob fixes this by expanding an unmatched pattern to no arguments at all.

#!/usr/bin/env bash
LC_ALL=C
# directory has no .md files at all
echo "-- default: no match on *.md --"
for f in *.md; do echo "  got: [$f]"; done
echo "-- nullglob on --"
shopt -s nullglob
for f in *.md; do echo "  got: [$f]"; done
echo "  (loop body ran 0 times)"
shopt -u nullglob

Output:

-- default: no match on *.md --
  got: [*.md]
-- nullglob on --
  (loop body ran 0 times)

With the default behaviour the loop runs once with f set to the literal string *.md, which is almost never what you want -- code that then tries to read that "file" fails with a confusing error about a file literally named with an asterisk. With nullglob set, the unmatched pattern vanishes, the for list is empty, and the body runs zero times. For any loop that iterates over files that might not exist, nullglob is close to mandatory. The reverse hazard, dotglob, makes * also match .hidden.txt and similar names, which is what you want for a thorough sweep and a disaster if you then delete the matches, because . and .. are excluded but every other dotfile is fair game.

extglob: compound patterns

With shopt -s extglob, five extended operators become available: ?(p) zero or one, *(p) zero or more, +(p) one or more, @(p) exactly one, and !(p) anything except. Each takes a pipe-separated list of sub-patterns.

#!/usr/bin/env bash
LC_ALL=C
shopt -s extglob
# files: alpha.txt beta.txt gamma.txt app1.log app2.log app10.log
#        data1.csv data2.csv data9.csv
echo "-- @(alpha|beta).txt --"; printf '%s\n' @(alpha|beta).txt
echo "-- app+([0-9]).log --";   printf '%s\n' app+([0-9]).log
echo "-- data?([0-9]).csv --";  printf '%s\n' data?([0-9]).csv

Output:

-- @(alpha|beta).txt --
alpha.txt
beta.txt
-- app+([0-9]).log --
app1.log
app10.log
app2.log
-- data?([0-9]).csv --
data1.csv
data2.csv
data9.csv

@(alpha|beta).txt matches exactly one of the two listed names, so gamma.txt is excluded. app+([0-9]).log matches app followed by one or more digits, so it now catches app10 as well as the single-digit names -- note the sort places app10 before app2 because byte order compares the 1 against the 2 at the third character. data?([0-9]).csv allows zero or one digit after data, which matches all three here. The !(...) operator is the most powerful and the most dangerous: !(*.log) matches everything that is not a log file, and it is the natural way to express "all the other files" -- but as the real-world example shows, keeping that negation in sync with the positive patterns is a genuine maintenance trap.


Real World Example: A Release-Artifact Auditor

A release directory should contain only the things you meant to ship: archives, their checksums, and nothing else. This auditor buckets the files by glob, counts each bucket, and sums its bytes, using nullglob so an empty bucket is genuinely empty and extglob so the "everything else" bucket can be expressed as a negation. The file set is fixed with known sizes so the totals are reproducible.

#!/usr/bin/env bash
set -u
LC_ALL=C
shopt -s nullglob extglob
# release/ holds, with these exact byte sizes:
#   app-1.2.0.tar.gz 4096   app-1.2.0.zip 2048   lib-1.2.0.tar.gz 1024
#   app-1.2.0.tar.gz.sha256 64   lib-1.2.0.tar.gz.sha256 64
#   README.md 512   notes.txt 256
dir=${1:-release}
cd "$dir" || exit 1

bucket() {
  local label=$1; shift
  local files=( "$@" )
  local count=${#files[@]} total=0 f sz
  for f in "${files[@]}"; do
    sz=$(wc -c < "$f")
    total=$(( total + sz ))
  done
  printf '%-10s %2d file(s) %6d bytes\n' "$label" "$count" "$total"
}

bucket "archives"  *.tar.gz *.zip
bucket "checksums" *.sha256
bucket "unexpected" !(*.tar.gz|*.zip|*.sha256)

Output:

archives    3 file(s)   7168 bytes
checksums   2 file(s)    128 bytes
unexpected  2 file(s)    768 bytes

Trace the buckets. The archives glob *.tar.gz *.zip collects the two tarballs and the one zip: three files totalling 4096 plus 1024 plus 2048, which is 7168 bytes. The checksums glob *.sha256 collects the two 64-byte checksum files, 128 bytes. The unexpected bucket uses !(*.tar.gz|*.zip|*.sha256) to catch everything that is not an archive or checksum, which is README.md and notes.txt, 512 plus 256 giving 768 bytes. A release process could treat a non-empty unexpected bucket as a warning that stray files are about to ship.

The bucket function is worth studying. It takes a label and then a variable number of filenames, captured with local files=( "$@" ). Because nullglob is set, a pattern that matches nothing contributes no arguments, so count is a true zero and the for loop runs no iterations -- without nullglob an empty bucket would show a phantom file whose name is the literal pattern, and wc -c would fail on it. The printf format uses fixed field widths so the columns line up regardless of the counts.

The honest limits are real and instructive. First and most serious, the unexpected negation must be kept in sync by hand with the positive buckets: add a *.tgz archive type to the archives bucket and forget to add it to the !(...) list, and every .tgz silently lands in unexpected, misreporting the audit. Second, the code assumes every match is a regular file -- if a subdirectory matches a glob, wc -c prints an "Is a directory" error and the byte total is wrong, so a real version would guard with [[ -f $f ]]. Third, overlapping patterns in a single bucket double-count: *.tar.gz *.gz would list each tarball twice, because the shell expands both globs independently and concatenates the results. None of these fails loudly; each just quietly produces a wrong number, which is exactly why an auditor needs auditing.


Common Mistakes

  1. Forgetting that an unmatched glob stays literal. Without nullglob, for f in *.md when no .md files exist runs the loop once with f set to the string *.md. Code that then opens "$f" fails on a file that does not exist. Set nullglob, or test [[ -e $f ]] at the top of the loop.
  1. Running rm with an unquoted glob you did not preview. rm * expands to every non-hidden name in the directory, and if the directory is not what you expected, the deletion is not what you expected either. Preview with printf '%s\n' * or ls first, and never combine a broad glob with a destructive command untested.
  1. Assuming globs match hidden files. * and *.txt skip names beginning with a dot by default, so a cleanup loop over * silently leaves .env and .gitignore in place. If you need them, set dotglob; if you are deleting, know that they survive.
  1. Quoting a glob so it never expands. "*.txt" in double quotes is a literal string, not a pattern -- the shell does not glob inside quotes. A loop over "*.txt" iterates once over the literal text. Leave globs unquoted so they expand, and quote only the resulting variable.
  1. Using extglob operators without enabling extglob. @(a|b) and !(*.log) are ordinary characters until shopt -s extglob is set; before that they either error or match literally. Enable extglob at the top of any script that relies on the extended operators.
  1. Expecting glob ranges to follow locale-independent order. [a-z] depends on the collation locale; in some locales it includes accented or uppercase letters unexpectedly. Set LC_ALL=C when you need byte-order ranges and reproducible sorting, especially in scripts that run on varied machines.
  1. Letting a directory match a file-oriented glob. A glob like *.bak can match a directory named old.bak, and a command expecting files then errors or misbehaves on it. Guard the loop body with [[ -f $f ]] when you mean regular files only.
  1. Overlapping patterns that double-count. Listing *.tar.gz *.gz in one command matches each tarball under both patterns, so it appears twice. The shell does not deduplicate across separate globs; use a single pattern that covers the set, or deduplicate deliberately.
  1. Keeping a negation bucket out of sync with positive patterns. !(*.zip|*.tar.gz) for "everything else" quietly misclassifies a new archive type the day you add it to the positive list but not the negation. Any !(...) used as a catch-all is a maintenance liability that needs a test.

Best Practices

  • Set nullglob for any loop over a maybe-empty file set. It turns an unmatched pattern into zero iterations instead of one iteration over literal pattern text, which is almost always the behaviour you actually want and removes a whole class of "file not found: *.log" bugs.
  • Preview a glob before handing it to a destructive command. Run printf '%s\n' <pattern> and read the list before rm, mv, or chmod acts on it. The expansion is deterministic, so what you preview is exactly what the command receives.
  • Pin the locale with LC_ALL=C for reproducible ranges and order. Bracket ranges and the sort order of expansions both depend on locale; fixing it to C gives byte semantics that behave identically on every machine and in every user's environment.
  • Guard loop bodies with a file-type test. [[ -f $f ]] || continue at the top of a glob loop skips directories, sockets, and dangling symlinks, so a command that expects a regular file is never handed something it cannot process.
  • Enable extglob explicitly at the top of the script. Do not rely on the interactive shell having it on; put shopt -s extglob near the top of any script that uses @(), !(), or the other extended operators, so the script behaves the same when sourced or run fresh.
  • Prefer a single covering pattern over overlapping globs. When one file could match two of your patterns, collapse them into one pattern or partition the space so buckets are disjoint. This avoids the double-count that overlapping globs produce silently.
  • Test the empty case and the catch-all case. Run your globbing code against a directory that matches nothing and against one containing an unexpected file type. Negation catch-alls and empty buckets are where globbing bugs hide, so make them explicit test inputs.
  • Quote the expanded variable, not the pattern. Write the glob unquoted so it expands, then quote the loop variable -- for f in *.txt; do process "$f"; done -- so filenames with spaces survive once the shell has produced them.

Practice Exercises

  1. Demonstrate the empty-match default. In a directory with no .md files, write a loop over *.md and print each value, first without nullglob and then with it. Show that the first version runs once with the literal pattern and the second runs zero times, and explain in a comment why the first would break a real file-reading loop.
  1. A dotfile-aware cleaner (dry run only). Write a script that lists every file a rm * would delete and, separately, every file it would leave behind because it is hidden. Use dotglob to reveal the second set. Print both lists and do not actually delete anything; explain the risk in a comment.
  1. Classify with extglob. Given a directory of mixed files, use @(), +(), and !() to split names into three named buckets and print the count of each. Include at least one file that could match two buckets and show how you keep the buckets disjoint so nothing is double-counted.
  1. Locale-sensitive range. Print the expansion of [a-z]* under LC_ALL=C and again under a locale of your choice, in a directory containing both uppercase and lowercase leading names. Explain in a comment which files move between the two results and why the collation locale is responsible.