Advanced Bash Scripting
Globs
Overview
In earlier lessons, we explored Bash parameter expansion—using operators like #
and %
(and their double variants ##
/%%
) to strip prefixes and suffixes from variable values. We even combined these with the wildcard *
to broaden matches.
Note
Globs (also called wildcards or pathname expansion patterns) differ from parameter expansion. They operate directly on filenames and strings in the shell, not on variable values.
What Are Globs?
Globs let you match file and directory names—or any arbitrary strings—using a concise pattern syntax. They’re simpler than regular expressions (no lookahead, named groups, etc.), but cover most everyday use cases:
Glob Pattern | Matches | Example |
---|---|---|
* | Zero or more characters | *.txt |
? | Exactly one character | file?.sh |
[abc] | Exactly one of the set (a, b, c) | report[12].pdf |
When to Use Globs vs. Regex
Feature | Globs | Regular Expressions |
---|---|---|
Simplicity | Very easy to write | More complex (advanced syntax) |
Common Use Case | File matching | Text parsing, validation |
Advanced Constructs | Not supported | Lookahead, named groups, etc. |
Learning Approach
To master globs, follow these steps:
- Gather Sample Strings
Assemble a broad list of filenames or test strings you need to match. - Identify Common Patterns
Group similar strings to pinpoint shared prefixes, suffixes, or character sets. - Select the Appropriate Glob
Choose from*
,?
, or bracket expressions ([ ]
) to cover your pattern. - Test with Shell Commands
Run a command likels
orecho
to verify that your glob matches the intended files:
# Matches all .log files starting with "app"
ls app*.log
If the output aligns with your expectations, your glob is correct!
Next Steps
In the following sections, we’ll apply these principles to real-world examples—filtering logs, batch-renaming files, and more. Let’s start by examining a directory of mixed files and crafting precise globs for each case.
Links and References
- Bash Reference Manual – Filename Expansion
- Regular Expressions on Wikipedia
- ShellCheck – Automated Shell Script Analysis
Watch Video
Watch video content