Basic

Wildcards

The shell expands a pattern into a list of names before the command runs. That expansion is the reason wildcards work, and the reason they sometimes match more than you meant. The pattern is not a filter inside the program, it is a list the program is handed.

What you will see

The literal pattern echoed back - nothing matched, which is the message to recognise.

About 1 min of reading

Try It

Preview an expansion before acting.

1

Set up mixed files

mkdir -p globdemo && touch globdemo/a.txt globdemo/b.txt globdemo/c.md

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Three files, two .txt.
2

Preview

echo globdemo/*.txt

Before you run it, say out loud what it will print. Then open the answer.

What it prints
The two .txt names, space separated. That is exactly what the command would receive.
3

See the no-match case

echo globdemo/*.jpg

Before you run it, say out loud what it will print. Then open the answer.

What it prints
The literal pattern echoed back - nothing matched, which is the message to recognise.

Data Flow

A pattern becomes a list of names.
1 Write the pattern
↓
2 The shell matches it against the directory
↓
3 The list replaces the pattern
↓
4 The command runs on the list
Why this works
Preview the expansion

Put echo in front of the pattern, or run ls on it, and read the list. Seeing the names is faster and more reliable than reasoning about what the pattern should match, especially under pressure.

Quoting stops expansion

'*.txt' is the literal text, not a list. That is the right thing when the pattern belongs to the program rather than the shell, which is the difference between grep patterns and file names.

Examples

Star and question mark

*.txt matches every name ending in .txt, log?.txt matches log with one character. The shell replaces the pattern with the matching names, so the command sees a list, not a pattern.

No match means the pattern is passed

When nothing matches, some shells hand the literal pattern to the command, which then complains about a file called *.txt. That message is the tell: nothing matched, and your assumption about the names was wrong.

Star is greedy and recursive is different

*.txt does not reach into subfolders. A pattern that should cover nested files needs a different tool, find, which walks the tree deliberately rather than expanding one level.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Redirects and pipes
Previous Lesson
Redirects and pipes
Next Lesson
Running a script
Running a script →