Before a command runs, the shell first reads the line you typed and replaces certain patterns with other text. This is called expansion. The two you'll use most: globs (*.log is replaced with the list of matching file names) and brace expansion (a pattern with curly braces: photo-{01..03}.jpg is replaced with three words). The examples in this lesson run in bash.
Picture telling a shop assistant, "get me everything whose label ends in .log". The shop assistant is the shell: the assistant finds the items, then hands them one by one to the cashier. The cashier is a program like ls or rm. The words "everything that ends in .log" are the pattern *.log, and the items are the matching file names. The cashier never hears the word "everything". The cashier only receives the items.
Globs: patterns for file names
Our example folder holds 13 files. Two of them start with a dot, so they're hidden:
.env .gitignore app.js file1.log file2.log fileab.log index.html
notes.txt photo-01.jpg photo-02.jpg photo-03.jpg readme.md style.css
| Pattern | Meaning | Example in this folder |
|---|---|---|
* |
zero or more characters of any kind | *.log becomes file1.log file2.log fileab.log |
? |
exactly one character | file?.log becomes file1.log file2.log |
[12] |
one character from the list inside the square brackets | photo-0[12].jpg becomes photo-01.jpg photo-02.jpg |
[n-p] |
one character from the range | [n-p]* becomes notes.txt photo-01.jpg photo-02.jpg photo-03.jpg |
[!f] |
one character other than the ones listed | [!f]* becomes everything not starting with f |
echo shows the result of the replacement:
$ echo file?.log
file1.log file2.log
$ echo [!f]*
app.js index.html notes.txt photo-01.jpg photo-02.jpg photo-03.jpg readme.md style.css
file?.logdoesn't matchfileab.log, because?is one character andabis two.- The shell always sorts the results in alphabetical order.
- The pattern has to match the whole name, start to end.
*.txtdoesn't matchnotes.txt.bak.
The shell runs the glob, not the program
rm *.log never reaches rm in that form. The shell first turns it into rm file1.log file2.log fileab.log, and only then does rm run. That's why it's a good habit to check with echo first. echo *.log shows exactly the list that would be deleted, without deleting anything.
One special rule: * and ? don't match a dot at the start of a name. echo * prints 11 files, without .env and .gitignore. For hidden files, write the dot yourself: echo .* prints .env .gitignore. (In bash 5.2 and newer, . and .. aren't included. In older bash, they appear too.)
When nothing matches
Guess first: in a folder without a single .ts file, what does echo *.ts print?
When a glob finds no file at all, bash leaves the pattern as it is, star included:
$ echo *.ts
*.ts
$ ls *.ts
ls: cannot access '*.ts': No such file or directory
ls receives the text *.ts, then looks for a file really named *.ts. There is no such file, so you get the error above. This is how bash behaves. zsh (the default shell on macOS) doesn't run the command at all, and answers zsh: no matches found: *.ts.
If you want a pattern that matches nothing to simply disappear, turn on the bash setting shopt -s nullglob. Careful: with nullglob, ls *.ts turns into just ls, so it shows every file instead.
In zsh, a pattern that matches nothing often breaks find . -name *.ts when the .ts files are only in a subfolder. zsh looks for *.ts in the current folder, finds nothing, and stops with no matches found before find runs. Put quotes around the pattern: find . -name '*.ts'. The quotes make the pattern reach find exactly as written, in both bash and zsh. In bash, without quotes, the pattern is first replaced with the names of the .ts files in the current folder, if there are any. Then find looks for the wrong name, or fails with an error when more than one file matches. The zsh setting that matches nullglob is setopt nullglob.
Brace expansion: making text, not finding files
Brace expansion only copies text, without looking at the folder at all. So the results appear even when the files don't exist.
$ echo photo-{01..05}.jpg
photo-01.jpg photo-02.jpg photo-03.jpg photo-04.jpg photo-05.jpg
$ echo {app,index}.html
app.html index.html
$ echo {1..10..2}
1 3 5 7 9
| Form | Result |
|---|---|
{a,b,c} |
a b c, split on commas |
{1..5} |
1 2 3 4 5 |
{01..03} |
01 02 03. When either end starts with 0, every number is made as long as the longest one |
{a..e} |
a b c d e |
{1..10..2} |
1 3 5 7 9, going up by 2 each step |
config.json{,.bak} |
config.json config.json.bak, the first choice is empty |
Leading zeros and steps like {1..10..2} need bash 4 or later, or zsh. The bash 3.2 that ships with macOS prints 1 2 3 for {01..03}, and leaves {1..10..2} as it is.
Everyday uses: mkdir -p project/{src,tests,docs} makes three folders with one command. cp config.json{,.bak} becomes cp config.json config.json.bak, so it makes a backup.
Braces run before globs. echo *.{js,css} first becomes *.js *.css. Then each word is matched against the file names: the result is app.js style.css. In bash, echo *.{js,ts} gives app.js *.ts, because *.ts matches nothing and stays as it is.
Globs aren't regex
Globs and regex are both patterns, but the rules differ. Globs are made for file names and are simpler. Regex is for text in general and far more powerful.
| Glob | Regex | |
|---|---|---|
* |
any characters, any number of them | repeat the character before it, zero or more times |
? |
exactly one character | the character before it is optional |
. |
a plain dot | any character |
How to turn a glob into a regex:
- The dot and other symbols except
*and?are escaped: they get a\in front, so they're read as plain characters. *becomes.*, and?becomes..- The pattern is anchored with
^at the start and$at the end, so it must match the whole text.
So *.txt is the regex ^.*\.txt$. Because the dot is escaped, note_txt doesn't match. Because of the anchor at the end, note.txt.bak doesn't match either.
Bash also has extra patterns once shopt -s extglob is on. The most useful one, !(pattern), means "everything except what matches": ls !(node_modules|dist) shows every file and folder except node_modules and dist (here | means "or", not a pipe). And after shopt -s globstar (bash 4 or later), ** matches folders at any depth: ls **/*.js shows the .js files in this folder and in all its subfolders. In zsh, ** works without any setting. On the other hand, !(pattern) does not work in zsh: zsh answers no matches found. In zsh, turn on setopt extendedglob, then write ls ^(node_modules|dist) (^ means "except").
⚠️ Check before a pattern deletes something
rmbeforeecho. Check the expansion withechofirst, then runrmormvwith the same pattern.- A pattern inside quotes.
ls "*.log"looks for a file really named*.log. Quotes turn globs and braces off. - Spaces inside the braces. In bash,
echo {a, b}prints as it is, because the space cuts it into two words. Write it without spaces:{a,b}. - Thinking braces look for files.
rm photo-{01..05}.jpgtries five names, and shows an error for the names that don't exist. Use a glob (photo-*.jpg) when you mean "only the ones that are there".
TL;DR: The shell replaces patterns before the program runs. Globs (patterns for file names) are matched against the file names that exist. In a glob, * is any characters, ? exactly one character, [abc] one character from the list, and [!abc] one character other than those. The pattern must match the whole name. * and ? don't match a dot at the start of a name (hidden files). When nothing matches, bash leaves the pattern as it is (unless the setting shopt -s nullglob is on). zsh (the default shell on macOS) does not run the command at all and answers no matches found, so put quotes around a pattern that must reach a program as written: find . -name '*.ts'. Brace expansion (a pattern with curly braces) makes text without looking at the folder: {a,b} becomes a b, {1..3} becomes 1 2 3, and {01..03} becomes 01 02 03. Braces run before globs. Globs aren't regex: a glob * is the regex .*, and a glob dot is a plain dot. With extglob (an extra bash setting), !(pattern) means everything except what matches. Check with echo before rm.
⚡ Globs: patterns for file names
Write:
echo *.log
echo file?.log
Meaning: In a folder with file1.log, file2.log and fileab.log, the shell replaces *.log with those three names before echo runs. * matches any characters, any number of them. ? is exactly one character, so file?.log doesn't match fileab.log (ab is two characters). The pattern must match the whole name.
⚡ The shell replaces it, not the program
Guess first: in bash, in a folder with no .ts files, what does echo *.ts print?
*.ts, exactly as written. When nothing matches, bash leaves the pattern alone. zsh (the macOS default) refuses the command with zsh: no matches found: *.ts.
Meaning: rm *.log has already become rm file1.log file2.log fileab.log before rm runs: the shell replaces the pattern, not rm. That's why you check with echo before deleting.
⚡ Braces: making text
Write:
mkdir -p project/{src,tests,docs}
echo photo-{01..05}.jpg
Meaning: Brace expansion (a pattern with curly braces) copies text without looking at the folder, so the result appears even when the files don't exist. The first line makes three folders: project/src, project/tests and project/docs. The second line prints photo-01.jpg to photo-05.jpg. Braces run before globs.
⚡ Globs aren't regex
Meaning: Globs are only for file names and their rules are simpler: * matches anything. Regex (a text pattern that can use special characters) is for text in general and far more powerful. The glob *.txt is the regex ^.*\.txt$: .* means any characters, \. a plain dot, and ^ and $ the start and the end of the text.