Understanding File Paths and Wildcards

Su Suriya Ravichandran Updated 06 Dec 2026
8 min read ·Lesson 22 of 205

Every command that works with files needs to know which files. A path tells Bash where a file is, and a wildcard lets you describe many files with a single pattern instead of typing each name. These two ideas appear in almost every command you will write, so it pays to understand exactly how they work.

Understanding Paths

A file system is a tree. At the top is the root directory, written /, and every file and directory hangs below it. A path is a route through that tree, with / separating the names along the way.

The examples in this lesson use a small web project. The shell is inside the site directory:

/home/user/
├── docs/
└── projects/
    └── site/
        ├── about.html
        ├── contact.html
        ├── index.html
        ├── notes.txt
        ├── .hidden
        ├── my file.txt
        ├── report_a.txt
        ├── report_ab.txt
        ├── report_b.txt
        ├── Report_C.txt
        ├── css/
        │   ├── main.css
        │   └── print.css
        └── img/
            ├── logo.png
            ├── photo1.jpg
            ├── photo2.jpg
            └── photo10.jpg

The pwd command prints the current directory:

pwd

Output:

/home/user/projects/site

Absolute Paths

An absolute path starts with / and describes the route from the root. It means the same thing no matter where you are:

ls /home/user/projects/site/css/main.css

Output:

/home/user/projects/site/css/main.css

Relative Paths

A relative path does not start with /. Bash reads it starting from the current directory. From site, the file main.css is reached through css:

ls css/main.css

Output:

css/main.css

Special Names in Paths

Four short names have a fixed meaning:

NameMeaning
.The current directory
..The parent directory, one level up
~Your home directory, such as /home/user
-The previous directory (used with cd)

The name . is useful when a command requires a path and you mean "here". The name .. can be repeated to climb several levels. All three of these commands name the same file:

ls css/main.css
ls ./css/main.css
ls ../site/css/main.css

Output of each:

css/main.css
./css/main.css
../site/css/main.css

The last one goes up to projects, then comes back down into site and on to css/main.css. The tilde is expanded by the shell before a command runs:

echo ~
cd ~/docs
pwd

Output:

/home/user
/home/user/docs

The command cd - returns you to the directory you were in before and prints its path. It uses the OLDPWD variable, which Bash updates on every cd.

When a directory is reached through a symbolic link, pwd shows the path you used to get there. The option -P prints the physical path, with all links resolved. In this project there are no links, so both print the same text.

How Wildcards Work

A wildcard, also called a glob pattern, is a pattern that Bash expands into a list of matching file names. The important point is who does the work: the shell expands the pattern before the command starts. The command never sees the wildcard; it receives the final list of names.

You can see this with echo, which just prints its arguments:

echo *.html

Output:

about.html contact.html index.html

Bash replaced *.html with the three matching names, in alphabetical order, and echo printed them. Running ls *.html is exactly the same as typing ls about.html contact.html index.html.

The Wildcard Characters

The Asterisk *

The * matches any number of characters, including none. It matches within one path component only, so it never matches the / between directories:

ls *.html
ls css/*.css

Output:

about.html
contact.html
index.html
css/main.css
css/print.css

The Question Mark ?

The ? matches exactly one character. With these files, report_?.txt matches a name with one character after the underscore, and report_??.txt matches names with two:

ls report_?.txt
ls report_??.txt

Output:

report_a.txt
report_b.txt
report_ab.txt

Character Sets with [ ]

Square brackets match one character out of a set or range:

ls report_[ab].txt
ls img/photo[0-9].jpg

Output:

report_a.txt
report_b.txt
img/photo1.jpg
img/photo2.jpg

The second pattern matches names with exactly one digit, so photo10.jpg is left out because it has two. To match anything except the listed characters, start the set with !:

ls report_[!a].txt

Output:

report_b.txt

Sets can also use named classes such as [[:digit:]], [[:lower:]] and [[:upper:]]. The classes behave the same in every language setting, which makes them safer than ranges like [A-Z]. In some locales a range such as [a-z] can also match uppercase letters.

Brace Expansion Is Different

Curly braces look similar, but they are not a wildcard. {a,b} generates text whether or not any file exists:

echo img/photo{1,2}.jpg

Output:

img/photo1.jpg img/photo2.jpg

Brace expansion is covered in its own lesson later. The rule to remember is that a glob only produces names of files that exist, and braces produce names regardless.

Rules You Need to Know

Hidden Files

A name that begins with a dot is hidden. The wildcard * does not match a leading dot, so .hidden is skipped:

ls *

Output:

Report_C.txt
about.html
contact.html
index.html
my file.txt
notes.txt
report_a.txt
report_ab.txt
report_b.txt

css:
main.css
print.css

img:
logo.png
photo1.jpg
photo10.jpg
photo2.jpg

Two things happen here. The hidden file is missing, and because css and img also match *, ls shows what is inside those directories. To include hidden files, use ls -A, or write the dot yourself with a pattern such as .h*. In Bash 5.2 and later, the pattern .* no longer matches the special entries . and .., so echo .* prints only .hidden here. Older versions also printed . and ...

Order of Results

Bash sorts the expanded names alphabetically according to your locale, and it compares text, not numbers:

ls img/photo*.jpg

Output:

img/photo1.jpg
img/photo10.jpg
img/photo2.jpg

photo10.jpg comes before photo2.jpg because the character 1 sorts before 2. The order of uppercase and lowercase names also depends on the locale: in this example Report_C.txt came first in the listing, but another system might place it after report_b.txt.

Quoting Turns Wildcards Off

Inside quotes, or after a backslash, a wildcard is just text:

echo *.html
echo "*.html"
echo '*.html'
echo \*.html

Output:

about.html contact.html index.html
*.html
*.html
*.html

Quote a pattern when a program should receive it unchanged. This is why find . -name "*.py" needs quotes: find does its own matching.

File Names with Spaces

The glob result keeps each name together, spaces included, because Bash treats every match as a separate argument:

ls my*

Output:

my file.txt

When you type a name with a space by hand, you must quote it or escape the space, as in "my file.txt" or my\ file.txt.

When Nothing Matches

If no file matches, Bash leaves the pattern in place as plain text:

ls *.pdf
echo *.pdf

Output:

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

ls received the literal text *.pdf, looked for a file with that exact name and failed. The echo line shows the same thing: the pattern passed through unchanged. This behavior surprises many people, because a script that loops over *.pdf runs once with the literal name when there are no PDF files.

Changing How Globs Behave with shopt

The shopt command turns Bash options on with -s and off with -u. Several options change how wildcards work:

OptionEffect
nullglobA pattern with no match expands to nothing
failglobA pattern with no match is an error
dotglob* also matches hidden files
nocaseglobMatching ignores case
globstar** matches files in all subdirectories

All of them are off by default. Here are the first three in action:

shopt -s nullglob
echo *.pdf
shopt -u nullglob

Output (an empty line, because nothing expanded):

shopt -s dotglob
echo *
shopt -u dotglob

Output:

.hidden Report_C.txt about.html contact.html css img index.html my file.txt notes.txt report_a.txt report_ab.txt report_b.txt

With failglob on, an unmatched pattern stops the command before it runs and Bash reports the problem:

bash: no match: *.pdf

The nocaseglob option makes the letter case irrelevant, so report_?.txt also matches Report_C.txt:

shopt -s nocaseglob
ls report_?.txt
shopt -u nocaseglob

Output:

Report_C.txt
report_a.txt
report_b.txt

Finally, globstar lets ** reach through any number of directory levels:

shopt -s globstar
ls **/*.css
shopt -u globstar

Output:

css/main.css
css/print.css

Changes made with shopt last only for the current shell session. In a script, put the shopt -s line near the top.

Practical Applications

Wildcards pair naturally with commands that change many files at once. Because the shell expands the pattern before the command runs, you can preview exactly what will be affected by putting echo in front of the command:

echo rm img/photo*.jpg

Output:

rm img/photo1.jpg img/photo10.jpg img/photo2.jpg

Nothing was deleted: echo only printed the command that Bash would have run, with the pattern already expanded. If that list is what you expected, remove the echo and run the command for real. If the list is wrong, you found the mistake before any file was touched.

Copying all web pages into a backup directory:

cp *.html ~/docs/

Counting the photos:

echo img/*.jpg | wc -w

Output:

3

Searching text only in the stylesheets. The css/*.css pattern expands to both stylesheet names, so grep receives two files and prints the file name in front of every match:

grep -n "color" css/*.css

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 Understanding File Paths and Wildcards and get answers drawn from it.

Signed-in readers only.