Wildcards, Globbing, and Brace Expansion
How Bash turns *, ?, [...], ** and extglob patterns into file names, how brace expansion differs, what happens when nothing matches, and how to view it all with tree.
By The Dark DebuggerUpdated 28 min read
This article covers the patterns Bash expands into file names (*, ?, [...], ** and the extended extglob forms), brace expansion, what happens when a pattern matches nothing, and how to look at the result with tree. You should already be comfortable moving around with cd and ls (Navigating the Filesystem) and creating, copying and deleting files (Working with Files and Directories). Everything here is used constantly in the rest of the track, starting with file permissions and finding files.
Why globbing is worth learning properly
Picture a server's log directory with a month and a half of access logs in it. You need to compress October's logs and leave November's alone. One pattern does it in a second. A slightly wrong pattern compresses the wrong month, or deletes the file the application is still writing to.
The thing that makes patterns predictable is one rule: the shell expands the pattern before the command runs. rm, ls and gzip never see the *. They receive a finished list of file names. Once that sinks in, you can always check what a pattern will do before you hand it to a destructive command.
Set up a practice directory
Every example below runs against the same small directory, so you can follow along and get identical output. The curly braces in the touch lines are brace expansion, which is covered later in this article; for now, trust that they create the files listed by ls.
mkdir -p ~/practice/globbing/logs && cd ~/practice/globbing/logs
touch access-2026-10-{28..31}.log access-2026-11-0{1..3}.log
touch access-2026-10-2{6,7}.log.gz error-2026-10-31.log error-2026-11-02.log
touch worker.log worker.log.{1,2,10} .rotation-state
ls -A.rotation-state access-2026-10-29.log access-2026-11-02.log worker.log
access-2026-10-26.log.gz access-2026-10-30.log access-2026-11-03.log worker.log.1
access-2026-10-27.log.gz access-2026-10-31.log error-2026-10-31.log worker.log.10
access-2026-10-28.log access-2026-11-01.log error-2026-11-02.log worker.log.2That is a realistic shape: daily access logs, two already compressed, error logs, a worker log rotated with numeric suffixes, and a hidden state file.
The shell expands the pattern, not the command
Run ls with a pattern:
ls *.logaccess-2026-10-28.log access-2026-10-30.log access-2026-11-01.log access-2026-11-03.log error-2026-11-02.log
access-2026-10-29.log access-2026-10-31.log access-2026-11-02.log error-2026-10-31.log worker.logIt looks like ls understood *.log. It didn't. Bash replaced *.log with every matching name in the current directory, sorted, and then ran ls with those names as arguments. You can prove that with echo, which knows nothing about files at all:
echo *.logaccess-2026-10-28.log access-2026-10-29.log access-2026-10-30.log access-2026-10-31.log access-2026-11-01.log access-2026-11-02.log access-2026-11-03.log error-2026-10-31.log error-2026-11-02.log worker.logprintf '%s\n' does the same thing with one name per line, which is easier to read when the list is long:
printf '%s\n' access-2026-11-*access-2026-11-01.log
access-2026-11-02.log
access-2026-11-03.logTo see the exact command line Bash builds, turn on tracing with set -x. Every command is printed with a + prefix after expansion and before it runs:
set -x
wc -c access-2026-11-*.log
set +x+ wc -c access-2026-11-01.log access-2026-11-02.log access-2026-11-03.log
0 access-2026-11-01.log
0 access-2026-11-02.log
0 access-2026-11-03.log
0 total
+ set +xPreview before you destroy
Before running rm, mv or gzip with a pattern, run echo with the same pattern first. It costs one second and shows you exactly which files the real command will receive.
The official name for this step is pathname expansion, and the patterns are often called globs (from an early Unix program called glob). "Wildcards", "globbing" and "pathname expansion" all mean the same thing in day-to-day use.
* and ?
* matches any string of characters, including the empty string. ? matches exactly one character. The difference matters with rotated logs:
ls worker.log.?
ls worker.log.??
ls worker.log.*worker.log.1 worker.log.2
worker.log.10
worker.log.1 worker.log.10 worker.log.2worker.log.? needs exactly one character after the dot, so it skips worker.log.10. worker.log.* takes any suffix. Neither matches plain worker.log, because both require the dot after log.
Two limits apply to every glob character:
- A glob never matches the
/between directories.*stays inside one directory level unless you use**(covered below). - A glob never matches a leading dot unless the pattern itself starts with a dot. That is why
.rotation-statedid not show up inecho *.log, and it is how "hidden" files stay hidden.
Also notice the sort order in that last line: worker.log.10 comes before worker.log.2. Globs sort as text, not as numbers.
Bracket expressions: [...]
A bracket expression matches one character from a set:
| Pattern | Matches one character that is… |
|---|---|
[01] | 0 or 1 |
[0-3] | in the range 0 to 3 |
[!z] or [^z] | anything except z |
[[:digit:]] | a digit |
[[:alpha:]] | a letter |
[[:upper:]] / [[:lower:]] | an upper- or lower-case letter |
[[:alnum:]] | a letter or digit |
[[:space:]] | whitespace |
Combined with fixed text, brackets let you pick precise date ranges out of the log directory:
ls access-2026-10-3[01].log
ls *-2026-1[01]-0[1-3].logaccess-2026-10-30.log access-2026-10-31.log
access-2026-11-01.log access-2026-11-02.log access-2026-11-03.log error-2026-11-02.logThe second pattern reads as "anything, then -2026-1, then 0 or 1, then -0, then 1 to 3, then .log". Only November's first three days exist in that range, from both the access and error logs.
Negation is handy for "everything that is not compressed". The last character of a .gz file is z, so:
echo access-*[!z]access-2026-10-28.log access-2026-10-29.log access-2026-10-30.log access-2026-10-31.log access-2026-11-01.log access-2026-11-02.log access-2026-11-03.logPOSIX character classes go inside a bracket expression, which is why they have double brackets:
echo worker.log.[[:digit:]]
echo *[[:digit:]][[:digit:]]worker.log.1 worker.log.2
worker.log.10A note on ranges such as [a-z]: in some older shells and locales, [a-z] also matched upper-case letters because the range followed the locale's collation order. Bash 5.2 has the globasciiranges option turned on by default, so [a-z] means the 26 ASCII lower-case letters. If you want to be explicit regardless of version, use [[:lower:]].
Hidden files and dotglob
Files whose names start with a dot are skipped by *:
echo *
echo .*access-2026-10-26.log.gz access-2026-10-27.log.gz access-2026-10-28.log access-2026-10-29.log access-2026-10-30.log access-2026-10-31.log access-2026-11-01.log access-2026-11-02.log access-2026-11-03.log error-2026-10-31.log error-2026-11-02.log worker.log worker.log.1 worker.log.10 worker.log.2
.rotation-stateShell options change how globbing behaves. You turn an option on with shopt -s name, off with shopt -u name, and check it with shopt name. The dotglob option makes * include hidden files:
shopt -s dotglob
echo *
shopt -u dotglob.rotation-state access-2026-10-26.log.gz access-2026-10-27.log.gz access-2026-10-28.log access-2026-10-29.log access-2026-10-30.log access-2026-10-31.log access-2026-11-01.log access-2026-11-02.log access-2026-11-03.log error-2026-10-31.log error-2026-11-02.log worker.log worker.log.1 worker.log.10 worker.log.2There is one version difference worth knowing. Every directory contains the entries . (itself) and .. (its parent). Older Bash versions included them in .*, which made commands like chmod -R go-w .* reach up into the parent directory. Bash 5.2 added the globskipdots option, on by default, that leaves them out. You can see the old behaviour by turning it off:
shopt globskipdots
echo .*
shopt -u globskipdots
echo .*
shopt -s globskipdotsglobskipdots on
.rotation-state
. .. .rotation-stateIf your scripts run on servers with older Bash, write .[!.]* to match hidden files without . and ...
When nothing matches: nullglob and failglob
This is the behaviour that surprises people most. When a pattern matches no files, Bash leaves the pattern in place, unchanged, and passes it to the command:
ls *.csv
echo *.csvls: cannot access '*.csv': No such file or directory
*.csvls received the literal string *.csv and went looking for a file with that name. In a loop the result is worse, because nothing fails:
for f in *.csv; do echo "importing $f"; doneimporting *.csvThe loop ran once with f set to the text *.csv. A real import script would now try to open a file called *.csv and fail with a confusing error, or worse, create one.
Two shell options change this. With nullglob, a pattern that matches nothing expands to nothing at all:
shopt -s nullglob
for f in *.csv; do echo "importing $f"; done
ls *.csvaccess-2026-10-26.log.gz access-2026-10-29.log access-2026-11-01.log error-2026-10-31.log worker.log.1
access-2026-10-27.log.gz access-2026-10-30.log access-2026-11-02.log error-2026-11-02.log worker.log.10
access-2026-10-28.log access-2026-10-31.log access-2026-11-03.log worker.log worker.log.2The loop printed nothing, which is correct. But look at ls *.csv: the pattern vanished, so Bash ran plain ls, which lists the whole directory. With rm or chmod -R, a vanished argument can mean "operate on the current directory" or "operate on nothing", depending on the command. That is why nullglob belongs in scripts that loop over files, not in your interactive shell.
With failglob, a pattern that matches nothing is an error and the command does not run at all:
shopt -u nullglob
shopt -s failglob
ls *.csv
echo "exit status: $?"
shopt -u failglobbash: no match: *.csv
exit status: 1| Setting | Pattern matches nothing → | Good for |
|---|---|---|
| default | the pattern is passed through literally | interactive use, where you read the error |
nullglob | the pattern disappears | for loops over files in scripts |
failglob | error, command is not run | scripts that must never act on a literal pattern |
My recommendation: leave the default at the prompt, and put shopt -s nullglob near the top of any script that loops over a glob. We'll come back to this in Loops, Functions, and Reading Input.
Recursive globbing with **
By default, ** means the same as *. So **/*.js matches .js files exactly one directory down, and nothing deeper. Let's build a small project to see this:
cd ~/practice/globbing
mkdir -p webapp/{src/routes,tests/routes,scripts,config,node_modules/{express,lodash}}
cd webapp
touch README.md package.json .env
touch src/{app,server}.js src/routes/{users,orders}.js
touch tests/app.test.js tests/routes/users.test.js
touch scripts/{deploy,backup}.sh config/{default,production}.yml
touch node_modules/express/{index.js,package.json} node_modules/lodash/lodash.js
echo **/*.jssrc/app.js src/server.js tests/app.test.jsTurn on globstar and ** matches any number of directory levels, including zero:
shopt -s globstar
echo **/*.js
printf '%s\n' **/*.test.jsnode_modules/express/index.js node_modules/lodash/lodash.js src/app.js src/routes/orders.js src/routes/users.js src/server.js tests/app.test.js tests/routes/users.test.js
tests/app.test.js
tests/routes/users.test.jsTwo more forms are useful. dir/** lists everything under a directory, and **/ (with the trailing slash) matches only directories:
printf '%s\n' src/**
printf '%s\n' **/
shopt -u globstarsrc/
src/app.js
src/routes
src/routes/orders.js
src/routes/users.js
src/server.js
config/
node_modules/
node_modules/express/
node_modules/lodash/
scripts/
src/
src/routes/
tests/
tests/routes/** is convenient, but it cannot filter by size, age or type, and it walks into directories you usually want to skip, like node_modules. For anything beyond "all files named like this", reach for find, covered in Finding Files with find, locate, and xargs.
Extended globs: extglob
The extglob option adds five pattern operators that work like small regular expressions. Each takes a list of patterns separated by |:
| Pattern | Matches |
|---|---|
?(list) | zero or one occurrence of the patterns |
*(list) | zero or more occurrences |
+(list) | one or more occurrences |
@(list) | exactly one of the patterns |
!(list) | anything except the patterns |
Back in the log directory:
cd ~/practice/globbing/logs
shopt extglob
shopt -s extglob
ls !(*.gz)
ls @(access|error)-2026-11-*.log
ls worker.log?(.+([0-9]))
ls access-2026-1@(0-3[01]|1-01).logextglob off
access-2026-10-28.log access-2026-10-31.log access-2026-11-03.log worker.log worker.log.2
access-2026-10-29.log access-2026-11-01.log error-2026-10-31.log worker.log.1
access-2026-10-30.log access-2026-11-02.log error-2026-11-02.log worker.log.10
access-2026-11-01.log access-2026-11-02.log access-2026-11-03.log error-2026-11-02.log
worker.log worker.log.1 worker.log.10 worker.log.2
access-2026-10-30.log access-2026-10-31.log access-2026-11-01.logReading them in order:
!(*.gz)is everything except compressed files. This is the pattern people want most often, for example "delete everything except the archives".@(access|error)-2026-11-*.logis November's logs of either kind.worker.log?(.+([0-9]))isworker.log, optionally followed by a dot and one or more digits. It matches the live log and all of its rotations, but would skip a file likeworker.log.old.access-2026-1@(0-3[01]|1-01).logis October 30 and 31 plus November 1: a date range that crosses a month boundary.
!(...) can also take several alternatives. "Everything except archives and worker logs" is:
echo !(*.gz|worker*)
shopt -u extglobaccess-2026-10-28.log access-2026-10-29.log access-2026-10-30.log access-2026-10-31.log access-2026-11-01.log access-2026-11-02.log access-2026-11-03.log error-2026-10-31.log error-2026-11-02.logextglob works at the prompt and fails in your script
On Ubuntu, the bash-completion package turns extglob on for interactive shells. When I checked shopt extglob in an interactive terminal with Ubuntu's default ~/.bashrc, it reported on. Scripts do not read ~/.bashrc, so in a script it is off, and an extglob pattern is not a pattern at all. It is a syntax error:
cd ~/practice/globbing
printf '%s\n' '#!/usr/bin/env bash' 'cd ~/practice/globbing/logs' 'ls !(*.gz)' > keep-recent.sh
cat keep-recent.sh
bash keep-recent.sh#!/usr/bin/env bash
cd ~/practice/globbing/logs
ls !(*.gz)
keep-recent.sh: line 3: syntax error near unexpected token `('
keep-recent.sh: line 3: `ls !(*.gz)'The fix is shopt -s extglob on its own line, before the line that uses the pattern. Bash parses a script line by line, and the option has to be on when the pattern is parsed, not just when it runs:
printf '%s\n' '#!/usr/bin/env bash' 'shopt -s extglob' 'cd ~/practice/globbing/logs' 'ls !(*.gz)' > keep-recent.sh
bash keep-recent.shaccess-2026-10-28.log access-2026-11-02.log worker.log.1
access-2026-10-29.log access-2026-11-03.log worker.log.10
access-2026-10-30.log error-2026-10-31.log worker.log.2
access-2026-10-31.log error-2026-11-02.log
access-2026-11-01.log worker.logPutting shopt -s extglob inside a function or on the same line as the pattern is not enough, for the same reason: the whole function or line is parsed before any of it runs.
Brace expansion
Brace expansion looks similar to globbing but is a completely different mechanism. It generates words from a template. It never looks at the filesystem.
A comma-separated list produces one word per item, with any text before and after the braces attached to each:
echo access-2026-11-0{1,2,3}.logaccess-2026-11-01.log access-2026-11-02.log access-2026-11-03.logTwo dots make a sequence. Numbers can be zero-padded (pad the first number and every result gets the same width), and a third number sets the step. Letters work too, in either direction:
echo {1..5}
echo {01..12}
echo {0..100..25}
echo {a..e} {z..v}1 2 3 4 5
01 02 03 04 05 06 07 08 09 10 11 12
0 25 50 75 100
a b c d e z y x w vSeveral braces in one word produce every combination, which is how you write out a fleet of host names without typos:
echo web{01..03}.{staging,prod}.example.comweb01.staging.example.com web01.prod.example.com web02.staging.example.com web02.prod.example.com web03.staging.example.com web03.prod.example.comBraces can also nest. One mkdir creates a whole project skeleton:
mkdir -p newproject/{src,tests/{unit,integration},docs}
tree newprojectnewproject
├── docs
├── src
└── tests
├── integration
└── unit
6 directories, 0 filesAn empty item is allowed, which gives you the classic "make a backup copy before editing" shortcut. Preview it with echo first:
cd ~/practice/globbing/webapp
echo cp config/production.yml{,.bak}
cp config/production.yml{,.bak}
ls config
echo mv README.{md,txt}cp config/production.yml config/production.yml.bak
default.yml production.yml production.yml.bak
mv README.md README.txtBrace expansion is not globbing
Because braces generate words without checking the disk, they produce names for files that do not exist:
echo report.{pdf,docx,odt}
ls report.{pdf,docx}report.pdf report.docx report.odt
ls: cannot access 'report.pdf': No such file or directory
ls: cannot access 'report.docx': No such file or directoryThat is exactly what you want for mkdir and touch, and exactly what you don't want when you meant "whichever of these exist". A common version of this mistake is ls *.{jpg,png} in a folder with no PNGs: the braces expand first into *.jpg *.png, then the globs run, and *.png matches nothing and is passed through literally, so ls complains about it.
Things that silently stay literal
Brace expansion has strict syntax, and when the syntax is wrong it does nothing at all instead of reporting an error:
n=5
echo {1..$n}
echo {a, b}
echo {single}
echo "{a,b}"
echo file.{txt}{1..5}
{a, b}
{single}
{a,b}
file.{txt}{1..$n}does not work because brace expansion happens before variables are expanded (see the order table below). By the time$nbecomes5, the brace step is already over. Useseq 1 "$n"or a C-styleforloop instead; both are shown in Loops, Functions, and Reading Input.- A space after the comma ends the word, so
{a, b}is two separate words that are not a brace expression. - One item with no comma or
..is not a brace expression. - Quotes switch brace expansion off.
Quoting turns expansion off
Quotes are how you pass a pattern to a command without the shell expanding it. Single quotes, double quotes and a backslash before the special character all work:
cd ~/practice/globbing/logs
echo '*.log'
echo "*.log"
echo \*.log*.log
*.log
*.logThe most common reason to do this is a command that does its own pattern matching, such as find -name, grep or tree -I. Those commands need to receive the pattern itself, not a list of files. The common mistakes section below shows what happens when you forget.
Quoting also matters for variables. A variable that holds a pattern is expanded and then globbed if you leave it unquoted:
pattern='access-2026-11-*'
echo $pattern
echo "$pattern"access-2026-11-01.log access-2026-11-02.log access-2026-11-03.log
access-2026-11-*That is occasionally what you want, but far more often it is a bug. A message like "Usage: * means all" stored in a variable will turn into a directory listing if you print it without quotes. The full story of quoting and variables is in Variables, Quoting, and the Environment.
The order of shell expansions
When Bash reads a command line, it applies its expansions in a fixed order. Most surprises in this article come from that order:
| Step | Expansion | Example |
|---|---|---|
| 1 | Brace expansion | file{1,2} becomes file1 file2 |
| 2 | Tilde, parameter and variable, arithmetic, command substitution, process substitution (left to right, all at the same step) | ~, $HOME, $((1+2)), $(date) |
| 3 | Word splitting (only on the results of unquoted step-2 expansions) | $var holding a b becomes two words |
| 4 | Pathname expansion (globbing) | *.log becomes the matching names |
| 5 | Quote removal | the quotes themselves are removed before the command runs |
A few experiments make the table concrete:
echo ~/practice/{globbing,missing}
n=3
echo {1..$n}
files='error-*.log'
ls $files
x='{a,b}'
echo $x
echo $(echo '*.gz')
echo "$(echo '*.gz')"/home/sid/practice/globbing /home/sid/practice/missing
{1..3}
error-2026-10-31.log error-2026-11-02.log
{a,b}
access-2026-10-26.log.gz access-2026-10-27.log.gz
*.gz- Line 1: braces run first and produce two words that both start with
~, then tilde expansion turns each~into the home directory. Neither path has to exist. - Line 2: as before,
$nis expanded after the brace step has already passed. - Line 3: the variable is expanded in step 2 and the result is globbed in step 4.
- Line 4: brace expansion never runs again on the result of a variable.
- Lines 5 and 6: the output of a command substitution is also globbed when unquoted, and left alone when quoted.
The authoritative reference is the Shell Expansions chapter of the Bash manual.
Visualising directories with tree
ls shows one directory at a time. tree draws the whole hierarchy, which is far easier to read when you are checking what a pattern or a mkdir -p actually built. It is not installed by default on many systems; on Ubuntu and Debian it comes from sudo apt install tree, on Fedora from sudo dnf install tree, and on macOS with Homebrew from brew install tree. (My test machine already had it, so I did not run the install commands here.)
With no options, tree shows everything below a directory except hidden files:
cd ~/practice/globbing
tree webappwebapp
├── README.md
├── config
│ ├── default.yml
│ ├── production.yml
│ └── production.yml.bak
├── node_modules
│ ├── express
│ │ ├── index.js
│ │ └── package.json
│ └── lodash
│ └── lodash.js
├── package.json
├── scripts
│ ├── backup.sh
│ └── deploy.sh
├── src
│ ├── app.js
│ ├── routes
│ │ ├── orders.js
│ │ └── users.js
│ └── server.js
└── tests
├── app.test.js
└── routes
└── users.test.js
10 directories, 16 filesOn a real project that output is thousands of lines long, so you almost always add options. -L limits the depth (and -d, which you saw with newproject above, shows directories only):
tree -L 1 webappwebapp
├── README.md
├── config
├── node_modules
├── package.json
├── scripts
├── src
└── tests
6 directories, 2 files-I hides anything matching a pattern. Note the quotes: this is a pattern for tree to match, not for the shell to expand, and | separates alternatives. Combine it with -a to show hidden files and --dirsfirst to group directories at the top:
tree -a -I 'node_modules|.git' --dirsfirst webappwebapp
├── config
│ ├── default.yml
│ ├── production.yml
│ └── production.yml.bak
├── scripts
│ ├── backup.sh
│ └── deploy.sh
├── src
│ ├── routes
│ │ ├── orders.js
│ │ └── users.js
│ ├── app.js
│ └── server.js
├── tests
│ ├── routes
│ │ └── users.test.js
│ └── app.test.js
├── .env
├── README.md
└── package.json
7 directories, 14 files-P does the opposite and shows only files that match. Add --prune so directories that end up empty are hidden:
tree -P '*.js' --prune -I node_modules webappwebapp
├── src
│ ├── app.js
│ ├── routes
│ │ ├── orders.js
│ │ └── users.js
│ └── server.js
└── tests
├── app.test.js
└── routes
└── users.test.js
5 directories, 6 filesThe full set of options used in this section, plus two that help when you paste tree output into a README:
| Option | Effect |
|---|---|
-L n | descend at most n levels |
-d | directories only |
-a | include hidden files |
-I 'pat' | exclude names matching the pattern (a|b for several) |
-P 'pat' | include only files matching the pattern |
--prune | hide directories that end up empty (pairs well with -P) |
--dirsfirst | list directories before files |
-F | append / to directories, * to executables |
--noreport | omit the "N directories, M files" line |
Where you'll use this
Globs and braces show up in nearly every shell session. These are the situations where they earn their keep.
Monthly log archiving. Here is the October clean-up from the start of the article, done the careful way: preview, compress, move, check.
cd ~/practice/globbing/logs
mkdir -p archive/2026-10
echo *-2026-10-*.log
gzip *-2026-10-*.log
mv *-2026-10-*.log.gz archive/2026-10/
ls
tree archiveaccess-2026-10-28.log access-2026-10-29.log access-2026-10-30.log access-2026-10-31.log error-2026-10-31.log
access-2026-11-01.log access-2026-11-03.log error-2026-11-02.log worker.log.1 worker.log.2
access-2026-11-02.log archive worker.log worker.log.10
archive
└── 2026-10
├── access-2026-10-26.log.gz
├── access-2026-10-27.log.gz
├── access-2026-10-28.log.gz
├── access-2026-10-29.log.gz
├── access-2026-10-30.log.gz
├── access-2026-10-31.log.gz
└── error-2026-10-31.log.gz
2 directories, 7 filesThe echo line showed exactly five uncompressed October logs before anything changed. gzip replaced each with a .gz file, and the mv pattern picked up those five plus the two that were already compressed. November's logs and the worker logs were never touched, because no pattern could match them. On a real server you would run the same commands from a monthly cron job, which System Monitoring and Scheduling with cron and systemd covers.
Other everyday uses:
- Project scaffolding.
mkdir -p newproject/{src,tests/{unit,integration},docs}builds a whole directory layout in one line, andtree -dconfirms it. - Safe edits on servers.
cp production.yml{,.bak}(or the same trick on an nginx or SSH config) before you edit gives you an instant rollback copy. - Fleet operations.
web{01..03}.{staging,prod}.example.comwrites out host lists for an SSH loop or an inventory file without typos. - Selecting by date in file names. Rotated logs, database dumps (
db-2026-11-0[1-7].sql.gz) and build artefacts usually have dates or version numbers in their names, which brackets select precisely. - Keeping only what matters.
rm !(*.gz)in a scratch directory, after previewing withecho !(*.gz), removes everything except the archives. - Showing structure in documentation.
tree -d -L 2 --noreportoutput is the standard way to describe a repository's layout in a README.
Common mistakes
Forgetting to quote a pattern meant for another command
find -name does its own matching, so its pattern must reach find untouched. Leave it unquoted and the result depends on what happens to be in the current directory. In a directory with two .js files you get an error:
cd ~/practice/globbing/webapp/src
find . -name *.jsfind: paths must precede expression: `server.js'
find: possible unquoted pattern after predicate `-name'?The shell turned the command into find . -name app.js server.js, and find had no idea what the extra server.js was for. GNU find even guesses the cause. In a directory with exactly one match, it is worse: there is no error, just a wrong answer.
cd ~/practice/globbing/webapp/tests
find . -name *.js./app.test.jsThe pattern became -name app.test.js, so find silently skipped routes/users.test.js. In a directory with no .js files at all, the unquoted pattern is passed through literally and the command happens to work, which is how this bug survives testing. The fix is always the same:
cd ~/practice/globbing/webapp/src
find . -name '*.js'./server.js
./app.js
./routes/orders.js
./routes/users.jsTreating "no match" as "nothing happens"
rm *.tmprm: cannot remove '*.tmp': No such file or directoryHarmless at the prompt, but in a script the same thing causes a loop to run once with a literal * in the variable, or a command to fail and stop the script. Use nullglob in scripts that loop over files, as shown above.
"Argument list too long"
A glob can expand to more text than the kernel allows on one command line. The limit is set by ARG_MAX, which was 2 MiB on my test system. Brace expansion hits it just as easily:
mkdir -p ~/practice/globbing/sessions && cd ~/practice/globbing/sessions
getconf ARG_MAX
touch sess_{000001..200000}.tmp2097152
bash: /usr/bin/touch: Argument list too longTo create the files anyway, generate the names with printf (a shell builtin, so the limit does not apply to it) and let xargs split them into batches that fit:
printf 'sess_%06d.tmp\n' {1..200000} | xargs touch
ls | wc -l
rm sess_*.tmp200000
bash: /usr/bin/rm: Argument list too longNow rm sess_*.tmp fails for the same reason. Session directories, mail spools and cache folders reach this size in real life. The fix is to let find do the matching, so the names never pass through a command line:
find . -name 'sess_*.tmp' -delete
ls | wc -l0xargs and find -delete are explained properly in Finding Files with find, locate, and xargs.
The other two traps from this article, an extglob pattern in a script without shopt -s extglob and a variable inside a brace sequence, were shown in their own sections above. Both fail quietly or confusingly, so they are worth re-reading.
Summary
- Bash expands globs before the command runs. The command receives a list of names; preview that list with
echoorprintf '%s\n', or trace it withset -x. *matches any string,?exactly one character,[...]one character from a set ([!...]negates;[[:digit:]]and friends are classes). None of them match/or a leading dot.dotglobmakes*include hidden files. Bash 5.2'sglobskipdotskeeps.and..out of.*; on older versions use.[!.]*.- A pattern that matches nothing is passed through literally by default.
nullglobmakes it disappear (use it for loops in scripts),failglobmakes it an error. globstarmakes**recurse into subdirectories;extglobadds?(),*(),+(),@()and!(). Turnextglobon withshopt -s extglobon its own line in scripts, even if it works at your prompt.- Brace expansion generates words from a template (lists,
{01..12},{0..100..25}, nested combinations) without looking at the disk. It runs first, so{1..$n}does not work. - Quote patterns meant for other commands (
find -name '*.js',tree -I 'node_modules'), and quote variables unless you deliberately want them globbed. tree -L,-d,-I,-P --prune,-aand--dirsfirstturn a directory into a readable picture.
Exercises
All exercises use the practice directory from the start of the article. If you ran the archiving example, recreate the logs first with rm -rf ~/practice/globbing/logs followed by the four setup commands.
In ~/practice/globbing/logs, write one pattern that matches every October log that is not yet compressed, both access and error logs, and preview it with echo. It should not match the two .gz files.
Show Solution
cd ~/practice/globbing/logs
echo *-2026-10-*.logaccess-2026-10-28.log access-2026-10-29.log access-2026-10-30.log access-2026-10-31.log error-2026-10-31.logThe leading * covers both the access and error prefixes. Ending the pattern with .log is what excludes the compressed files: a glob has to match the whole name, and access-2026-10-26.log.gz does not end in .log.
With a single mkdir command, create a directory api-service under ~/practice/globbing containing cmd/server, internal/handlers, internal/storage, deploy/staging and deploy/prod. Then show only the directories with tree.
Hint
Nest braces inside braces, and remember the -p flag so parent directories are created.
Show Solution
cd ~/practice/globbing
mkdir -p api-service/{cmd/server,internal/{handlers,storage},deploy/{staging,prod}}
tree -d api-serviceapi-service
├── cmd
│ └── server
├── deploy
│ ├── prod
│ └── staging
└── internal
├── handlers
└── storage
9 directoriesThe braces expand to five paths (api-service/cmd/server, api-service/internal/handlers and so on), and mkdir -p creates each one along with any missing parents. tree sorts names alphabetically, which is why deploy appears before internal even though it was written last.
Write a script import.sh in a new directory ~/practice/globbing/imports. It should print importing NAME for every .csv file in the current directory and then done. When there are no CSV files, it must print only done. Test it with no CSV files, then create customers.csv and orders.csv and test again.
Show Solution
mkdir -p ~/practice/globbing/imports && cd ~/practice/globbing/imports
printf '%s\n' '#!/usr/bin/env bash' 'shopt -s nullglob' 'for f in *.csv; do' ' echo "importing $f"' 'done' 'echo "done"' > import.sh
cat import.sh
bash import.sh
touch customers.csv orders.csv
bash import.sh#!/usr/bin/env bash
shopt -s nullglob
for f in *.csv; do
echo "importing $f"
done
echo "done"
done
importing customers.csv
importing orders.csv
doneWithout shopt -s nullglob, the first run would print importing *.csv, because an unmatched pattern is passed through literally. With it, the pattern expands to nothing and the loop body never runs. (You can of course write the script in an editor instead of with printf.)
In a freshly set up ~/practice/globbing/logs, use one extended glob to list every file that is neither compressed (.gz) nor a worker log. The hidden .rotation-state file should not appear.
Show Solution
cd ~/practice/globbing/logs
shopt -s extglob
echo !(*.gz|worker*)
shopt -u extglobaccess-2026-10-28.log access-2026-10-29.log access-2026-10-30.log access-2026-10-31.log access-2026-11-01.log access-2026-11-02.log access-2026-11-03.log error-2026-10-31.log error-2026-11-02.log!(list) matches any name that matches none of the patterns in the list. Hidden files stay out because, like every glob, !(...) does not match a leading dot unless dotglob is on. In a script, the shopt -s extglob line must come before the line containing the pattern.
In ~/practice/globbing/webapp, list every .js file at any depth except those under node_modules, using only globbing (no find, no grep). Then explain why **/*.js alone is not enough.
Hint
!(node_modules) matches every top-level entry except one. What could you put after it?
Show Solution
cd ~/practice/globbing/webapp
shopt -s globstar extglob
echo !(node_modules)/**/*.js
shopt -u globstar extglobsrc/app.js src/routes/orders.js src/routes/users.js src/server.js tests/app.test.js tests/routes/users.test.js**/*.js matches at every depth, including inside node_modules, and globs have no "exclude this directory" switch. Splitting the path solves it: !(node_modules) picks every top-level entry except node_modules, and /**/*.js then searches recursively inside each of those. Because ** can match zero directories, src/app.js is found as well as src/routes/users.js. One limitation: a .js file sitting directly in webapp/ would be missed, since the pattern requires at least one directory. When exclusions get this involved, find with -prune is usually clearer.
Tested with: GNU Bash 5.2.21 on Ubuntu 24.04 (WSL2), November 2026, with tree 2.1.1 and GNU findutils 4.9.0. Every command was run as shown in a fresh practice directory, in an interactive shell started without startup files (so extglob began switched off). ls sizes its columns to the terminal width, so your listings may wrap differently. The package-manager install commands for tree were not run because it was already installed.
Written by The Dark Debugger
Engineer documenting the things that took me too long to learn, so they take you less time. Every Bash tutorial here is tested end to end before publishing.