Advanced

Finding files by rule

find walks a tree and applies tests, which is the right tool once the rule is more than a name pattern: by age, by size, by type. Its syntax is unusual and its output is a list you can act on, which is where the power is.

What you will see

Only t/keep.md remains.

About 1 min of reading

Try It

Find, preview, then act.

1

Make nested files

mkdir -p t/sub && touch t/a.log t/sub/b.log t/keep.md

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

What it prints
Three files at two levels.
2

Preview

find t -type f -name '*.log'

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

What it prints
t/a.log and t/sub/b.log - both levels, which a single glob would have missed.
3

Act on the same rule

find t -type f -name '*.log' -delete && find t -type f

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

What it prints
Only t/keep.md remains.

Data Flow

A tree is walked and filtered.
1 Start at a narrow path
↓
2 Apply the tests
↓
3 Print the matches
↓
4 Act only after reading the list
Why this works
Bound the search

A find from the root of a large tree can take minutes and touch things you did not mean. Start the path narrow and add -maxdepth when you only want one or two levels, so the search costs what the question costs.

Time tests are about content

-mtime measures modification, not access, and copying a file resets it. A rule based on dates is only as good as the history of the files, which is worth checking before trusting the set it returns.

Examples

Tests combine with and

find . -type f -name '*.log' -mtime +7 finds files, regular ones, with that name, modified more than seven days ago. Each test narrows the set, and order barely matters for correctness.

Act with -exec or -delete

-exec rm {} \; runs a command per match and -delete removes them. Both are destructive, so run the same find without the action first and read the list it prints.

Names with spaces survive

Piping find output into xargs breaks on spaces. -print0 with xargs -0 uses a byte that cannot appear in a name, which is the correct pairing whenever names are unknown.

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.

← Variables and quoting
Previous Lesson
Variables and quoting
Next Lesson
Loops and conditionals
Loops and conditionals →