Filename Expansion and Globbing

Su Suriya Ravichandran Updated 06 Dec 2026
9 min read ·Lesson 52 of 205

Filename expansion, also called globbing or pathname expansion, is how Bash turns a pattern such as *.txt into the list of files that match it. You type the pattern; Bash searches the directory, builds the list of matching names, and hands that list to the command. The command itself never sees the pattern.

Understanding the Concept

Many commands need to work on groups of files: all text files, every report from last month, every image in a folder. Typing each name would be slow, so the shell lets you describe a group with a pattern. A pattern is made of ordinary characters, which match themselves, and special characters, which match many possibilities.

The key idea is that the shell does the matching, not the command. When you run ls *.txt, Bash expands *.txt first, and ls receives a plain list of names. The echo command is a good way to see what the shell produces, because it prints its arguments exactly as it received them.

The examples in this lesson use a folder created like this:

mkdir -p globdemo/docs globdemo/empty
cd globdemo
touch a.txt b.txt c.md notes.txt "my file.txt" A.TXT
touch report1.csv report2.csv report10.csv file.tar.gz .hidden
touch docs/x.txt docs/y.md

How Bash Expands a Pattern

Bash checks every word of a command after it has finished the earlier expansions. A word that contains an unquoted *, ? or [ is treated as a pattern. Bash then:

  1. Reads the names in the directory the pattern refers to.
  2. Keeps the names that match the whole pattern.
  3. Sorts the matches.
  4. Replaces the pattern with the sorted names, one word per name.

If no name matches, Bash leaves the pattern as it was (this default can be changed, as described later).

echo *.txt

Output:

a.txt b.txt my file.txt notes.txt

echo received four arguments. The file A.TXT was not included, because matching is case-sensitive.

Pattern Characters

PatternMatches
*Any sequence of characters, including none
?Exactly one character
[abc]One character from the list
[a-c]One character in the range
[!abc] or [^abc]One character that is not in the list
[[:class:]]One character from a named class

The Asterisk and the Question Mark

echo *
echo report?.csv
echo report??.csv

Output:

A.TXT a.txt b.txt c.md docs empty file.tar.gz my file.txt notes.txt report1.csv report10.csv report2.csv
report1.csv report2.csv
report10.csv
  • * alone matched every visible name in the folder, including the folders docs and empty.
  • report?.csv needs exactly one character between report and .csv, so report10.csv, which has two, did not match.
  • report??.csv needs exactly two characters, so only report10.csv matched.

Lists and Ranges

echo [ab].txt
echo [a-c].*
echo report[0-9].csv
echo report[!1].csv
echo report[^1].csv

Output:

a.txt b.txt
a.txt b.txt c.md
report1.csv report2.csv
report2.csv
report2.csv

Square brackets match one character. [ab] accepts a or b. [a-c] accepts any character from a to c. A ! (or ^) at the start reverses the list, so report[!1].csv means "report, then any one character except 1, then .csv". The ! form is the standard one; [^...] works in Bash but not in every shell.

Character Classes

Named classes avoid depending on alphabets and ranges. They are written inside the brackets, so you see two pairs:

echo [[:upper:]].TXT
echo report[[:digit:]].csv
echo [[:digit:]]*

Output:

A.TXT
report1.csv report2.csv
[[:digit:]]*

The common classes are [:alpha:], [:digit:], [:alnum:], [:upper:], [:lower:] and [:space:]. The last command shows what happens when nothing matches: no file name starts with a digit, so the pattern was printed unchanged.

Wildcards and Directories

A wildcard never matches the slash that separates directory names. A pattern must spell out each directory level, although each level can use wildcards of its own:

echo docs/*
echo */
echo */*.txt

Output:

docs/x.txt docs/y.md
docs/ empty/
docs/x.txt
  • docs/* matched everything inside docs.
  • */ matched only directories, because the trailing slash can only belong to a directory.
  • */*.txt looked inside every directory for .txt files and found only docs/x.txt. The a.txt and b.txt files in the current folder are not found, since the pattern requires one directory level.

Hidden Files

Names that start with a dot are hidden. A pattern does not match a leading dot unless the pattern itself starts with a dot:

echo .h*
echo .*

Output:

.hidden
.hidden

Plain * never produced .hidden. In Bash 5.2 and later, a pattern such as .* also skips the special entries . and .. (the globskipdots option, which is on by default), so only .hidden matched. Older versions of Bash include . and .. in this list, which can cause surprises with commands such as rm.

Sorting and Locale

Bash sorts the matches according to the current locale. In the default C locale, used for the examples here, capital letters sort before lowercase letters, and names are compared character by character:

echo report*.csv

Output:

report1.csv report10.csv report2.csv

The comparison is alphabetical, not numeric, so report10.csv appears before report2.csv. In other locales, the relative order of upper and lower case names can differ, so a script should not depend on it. Zero-padded names such as report01.csv and report02.csv keep a natural order.

Spaces and Special Characters in Matched Names

Each matched name becomes exactly one word, even if it contains spaces. Bash does not split the results again:

printf '[%s]\n' my*

Output:

[my file.txt]

echo hides this, since it joins its arguments with spaces. printf with a [%s] format shows the true word boundaries. This is why a loop such as for f in *.txt is safe with unusual names, while building a list of names as text and splitting it later is not.

When Nothing Matches

If no file matches, the pattern stays in the command as ordinary text:

echo *.xyz
ls *.xyz

Output:

*.xyz
ls: cannot access '*.xyz': No such file or directory

echo printed the pattern because there was nothing to replace it with. ls tried to open a file literally named *.xyz and failed, with exit status 2. Scripts that loop over *.log need to cope with this case, because the loop body would run once with the text *.log as the "file name". Shell options, described below, offer better behavior.

Quoting Turns Globbing Off

Quotes and backslashes make the special characters ordinary:

echo "*.txt"
echo '*.txt'
echo \*.txt

Output:

*.txt
*.txt
*.txt

This is how you pass a pattern to a command that does its own matching, such as find -name "*.txt", instead of letting the shell expand it first.

Globs in Variables

A pattern stored in a variable stays a pattern. Whether it is expanded depends on quotes at the moment of use:

pat='*.md'
echo $pat
echo "$pat"

Output:

c.md
*.md

The unquoted $pat is expanded to its value and then treated as a pattern, so it matched c.md. The quoted version keeps the text unchanged. Later lessons on word splitting and quoting variables explain this behavior in detail.

Using Globs in Loops and Arrays

A for loop receives each match as one item:

for f in *.csv; do echo "file: $f"; done

Output:

file: report1.csv
file: report10.csv
file: report2.csv

A pattern can also fill an array, which lets you count the matches:

files=(*.txt)
echo "${#files[@]} files: ${files[*]}"

Output:

4 files: a.txt b.txt my file.txt notes.txt

Shell Options That Change Globbing

Several shopt options change how patterns behave. Turn an option on with shopt -s name and off with shopt -u name.

OptionEffect
nullglobA pattern with no matches expands to nothing
failglobA pattern with no matches is an error, and the command does not run
dotglobPatterns also match names that start with a dot
nocaseglobMatching ignores letter case
globstar** matches files and directories recursively

nullglob

shopt -s nullglob
echo *.xyz
set -- *.xyz
echo "count=$#"
shopt -u nullglob

Output (the first line is empty):


count=0

The pattern vanished, which is exactly what a loop over possibly-missing files needs: with nullglob, for f in *.log runs zero times when there are no logs.

failglob

shopt -s failglob
echo *.xyz
echo "status=$?"
shopt -u failglob

Output:

bash: no match: *.xyz
status=1

The command echo never ran. In a script, the message also names the script and line number.

dotglob

shopt -s dotglob
echo *
shopt -u dotglob

Output:

.hidden A.TXT a.txt b.txt c.md docs empty file.tar.gz my file.txt notes.txt report1.csv report10.csv report2.csv

nocaseglob

shopt -s nocaseglob
echo *.txt
shopt -u nocaseglob

Output:

A.TXT a.txt b.txt my file.txt notes.txt

Now A.TXT matched too.

globstar

shopt -s globstar
echo **/*.txt
shopt -u globstar

Output:

a.txt b.txt docs/x.txt my file.txt notes.txt

With globstar, **/ stands for "any number of directories, including none", so the pattern found the files in the current folder and in docs.

GLOBIGNORE and set -f

The variable GLOBIGNORE holds a colon-separated list of patterns that are removed from the results:

GLOBIGNORE='b.txt'
echo *.txt

Output:

a.txt my file.txt notes.txt

Setting GLOBIGNORE has a side effect: it also turns on dotglob behavior, and clearing the variable afterwards did not turn it off again in Bash 5.2.21. Set it inside a subshell, written as ( GLOBIGNORE=...; commands ), so the effect does not leak into the rest of the script.

Finally, set -f turns filename expansion off completely, and set +f turns it back on:

set -f
echo *.txt
set +f
echo *.txt

Output:

*.txt
a.txt b.txt my file.txt notes.txt

Globs Are Not Regular Expressions

Glob patterns look similar to regular expressions but follow different rules. Do not mix them up:

MeaningGlobRegular expression
Any text*.*
Any one character?.
Files ending in .txt*.txt.*0txt$

A glob is matched against the entire name, so *.txt must end with .txt. Commands such as grep use regular expressions, which is why grep "*.txt" file does not mean "files ending in .txt".

Previewing a Glob Before Using It

Because patterns can match more than you expect, it is wise to look at the expansion before running a command that changes or deletes files. Replace the command with echo, check the result, and then run the real command:

echo report*.csv

Output:

report1.csv report10.csv report2.csv

If the list is what you intended, repeat the line with the real command in place of echo.

Availability in Other Shells

The characters *, ? and [...] work in every POSIX shell. Dash, for example, expands *.txt and [!a]*.txt the same way as Bash. The negation written with a caret, [^a], is a Bash habit: in Dash the caret is an ordinary character, so [^a].txt matched a.txt there. Use [!a] in scripts that must run under sh. The options nullglob, failglob, dotglob, nocaseglob and globstar are Bash features, and extended patterns are covered in a later lesson on pattern matching.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Filename Expansion and Globbing and get answers drawn from it.

Signed-in readers only.