Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

find: search for files by name, size and date

By updated

Improve this page

A disk is filling up and you want to know which logs are more than a week old, or you are looking for a script filed "somewhere" in a project. find goes down into a folder, examines every file and prints the ones that pass your tests: name, type, size, modification date. It can also run a command on each file it finds. You write these searches on a small folder whose exact content you know, and the deletions are done on a copy.

The lesson Find files presents find next to grep and locate, which reads an indexed database whereas find walks the disk. Here, find is covered alone, up to pruning folders and running commands. To search for text inside files, see grep; to build commands from a list, see xargs.

What you will learn

  • Search for a file by its name, taking the case into account
  • Filter by type, depth, permissions and owner
  • Search by size without falling into the rounding trap
  • Search by modification date, and understand why -mtime +7 does not mean "more than 7 days"
  • Combine tests with OR and parentheses
  • Avoid entering a folder with -prune
  • Run a command on the files found, and delete on a copy after checking the list

Prerequisites

You know how to open a Linux terminal, create a folder and move into it with cd. Two notions help later: redirections and pipes (|, 2>/dev/null), and shell wildcards (*): the shell replaces them before it runs the command, which explains the quotes around the patterns.

Create the practice folder

All the examples run on the same files. The commands below create ~/find-lab with files of various names, sizes and dates, a folder interdit that an ordinary account cannot open (root can), a broken symbolic link and a file whose name contains a space.

Terminal window
mkdir ~/find-lab && cd ~/find-lab && {
mkdir node_modules src .git interdit
echo "rapport du mois" > rapport.txt
echo "Report anglais" > Report.txt
echo "cache" > .cache.log
touch vide.txt
head -c 500 /dev/zero > petit-500.bin
head -c 61440 /dev/zero > gros.log
echo "port=8080" > app.conf
echo "console.log(1)" > node_modules/a.js
echo "console.log(2)" > src/b.js
echo "[core]" > .git/config
ln -s inexistant lien-casse
echo "secret" > interdit/secret.txt
chmod 000 interdit
touch -d "2020-01-01" ancien.tar
echo "espace" > "mon fichier.txt"
echo "j7" > vieux-7j.log
touch -d "180 hours ago" vieux-7j.log
echo "j8" > vieux-8j.log
touch -d "193 hours ago" vieux-8j.log
printf '#!/bin/sh\necho ok\n' > run.sh
chmod 755 run.sh
chmod 600 app.conf
}

The braces group the commands behind the &&: they only run if mkdir ~/find-lab succeeds. If the folder already exists, mkdir refuses and nothing else is written. To start from scratch, delete the old folder (section "Clean up the practice folder"). Check the result with ls -la: interdit must have no permission at all (d---------), lien-casse must point to inexistant, which does not exist, and the two vieux- files must carry dates from the previous week.

The file names and the text inside the files are in French, like the words printed by echo: rapport is "report", interdit "forbidden", lien-casse "broken link", vieux "old", gros "big", petit "small", ancien "former", vide "empty", appel "call". Only the explanations are in English.

The outputs come from GNU findutils 4.10.0 (Debian 13, AlmaLinux 10.3, Ubuntu 26.04 LTS); find --version | head -1 prints your version. The messages are in English. The order of the lines depends on the file system: compare the lists without taking it into account.

One point matters for everything else: interdit is a folder you cannot open. Any command that goes down into ~/find-lab prints find: ‘./interdit’: Permission denied on standard error and returns exit code 1, even when it found files. The outputs below keep this line; on your machine, it may appear at another place.

The outputs of the section on dates assume that you run them within twelve hours of creating the folder: vieux-7j.log is 180 hours old at creation, and after twelve hours it reaches 8 whole days. After that, recreate the folder.

The find command in detail

A find command is always written in the same order: the starting folder, the options that set how deep find goes, the tests that keep or discard each path, then the action. With no action, find adds -print, which prints the path of each file kept. Read the line from left to right: each number refers to the explanation of that part.

Anatomy of the command

Syntaxfind [start...] [options] [tests] [action]

  1. find the programThe command run in the shell.
  2. projet the starting pointoptionalThe directory to walk. Without it, GNU find starts from the current directory.
  3. -maxdepth 1 a walk optionoptionalLimits how far down to go. It is written before the tests.
  4. -type f a testoptionalThe type: f file, d directory, l symbolic link.
  5. -name '*.log' another testoptionalThe name, between single quotes. Two tests in a row: both must pass.
  6. -print the actionoptionalWhat to do with the kept paths: -print, -exec, -delete. With no action, find prints.

Outputprojet/app.log

How find walks a directory, path by path

find examines each path in turn and applies the tests to it from left to right. The next map works on a small folder projet of six paths, with its own practice folder: create it separately.

Terminal window
mkdir -p ~/find-carte && cd ~/find-carte
mkdir -p projet/vieux.log projet/src
head -c 61440 /dev/zero > projet/app.log
echo trace > projet/src/debug.log
touch -d "193 hours ago" projet/src/debug.log
echo "console.log(1)" > projet/src/main.js

Before you turn on the options of the map, predict: for find projet -type f -name '*.log', how many paths does find examine, and how many files does it print? Ask the same question with -maxdepth 1, with -delete instead of the print, then with both. Then check on the map: look at the "Path n of t" counter and the output list.

Mental model

How find walks a directory

take a pathrun the tests, left to rightact and start again, path after path

$ find projet -type f -name '*.log'

  1. find reaches projet. It is a directory: -type f fails, find does not evaluate the rest and moves to the next path.
  2. find reaches app.log. It is a regular file: -type f succeeds, find moves to the next test.
  3. -name '*.log' succeeds. Every test passes: only the action is left.
  4. No action is written: find behaves as if -print were there, and prints the path.
  5. find reaches vieux.log. The name ends in .log, but it is a directory: -type f fails. Without this test, it would be kept.
  6. find reaches src. It is a directory: -type f fails, find does not evaluate the rest and moves to the next path.
  7. find reaches debug.log. It is a regular file: -type f succeeds, find moves to the next test.
  8. -name '*.log' succeeds. Every test passes: only the action is left.
  9. No action is written: find behaves as if -print were there, and prints the path.
  10. find reaches main.js. It is a regular file: -type f succeeds, find moves to the next test.
  11. -name '*.log' fails: the name does not end in .log. The file is rejected.
  12. No more paths. The disk has not changed: find only printed a list.

What the animation shows

  1. Everything is walked, hidden directories included: find goes down everywhere, unless -maxdepth or -prune stops it.
  2. Tests are read left to right, joined by AND. At the first one that fails, find moves to the next path.
  3. A name does not give a type: -name '*.log' also keeps a directory named vieux.log. -type f rejects it.
  4. With no action, find prints. That is -print. -exec and -delete act on the kept paths.

Golden rules

Read the list before deleting

Run the search with no action, read it, then add -delete at the end: placed before the tests, it would delete everything.

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

Put patterns in quotes

Without them, the shell replaces *.log with the files of the current directory before starting find.

find . -name '*.log'

Essential vocabulary

Tests · keep or reject each path

-type
By type: f file, d directory, l linkfind projet -type d → 3 directories
-name
By name, with wildcardsfind projet -name '*.log' → 3 paths
-size +50k
More than 50 KiBfind projet -size +50k → projet/app.log
-mtime +7
Modified at least 8 full days agofind projet -mtime +7 → projet/src/debug.log

Walk and actions · where to go down, what to do

-maxdepth 1
Do not go down more than one levelfind projet -maxdepth 1 -name '*.log' → 2 paths
!
Invert a testfind projet -type f ! -name '*.log' → projet/src/main.js
-exec … \;
Run a command per kept pathfind projet -name '*.js' -exec basename {} \; → main.js
-delete
Delete the kept pathsfind projet -name '*.js' -delete → main.js deleted, empty screen

Search by name: -name, -iname and quotes

-name compares the file name with a pattern and tells uppercase from lowercase. Search for the files whose name starts with report.

Terminal window
cd ~/find-lab
find . -name 'report*'
Output
find: ‘./interdit’: Permission denied

No file is printed: Report.txt starts with an uppercase letter, and rapport.txt is spelled with two p. -iname ignores the case.

Terminal window
find . -iname 'report*'
Output
find: ‘./interdit’: Permission denied
./Report.txt

The pattern goes between single quotes. Without them, the shell replaces *.log with the file names of the current folder before it runs find, which then receives arguments you did not write:

Terminal window
find . -name *.log
Output
find: paths must precede expression: `vieux-7j.log'
find: possible unquoted pattern after predicate `-name'?

The shell turned the command into find . -name gros.log vieux-7j.log vieux-8j.log: -name took gros.log, and find refuses the next name. The second message points to the cause. The pattern applies to the file name, without its folder, and follows the syntax of shell wildcards (*, ?, [ ]), not that of regular expressions. For a regular expression, -regex applies to the full path: find . -regex '.*\.log$'.

An empty result with Permission denied does not say that the file does not exist: it says that find could not look. find . -name 'secret*' does not find interdit/secret.txt, and echo $? gives 1.

Filter by type, depth and permissions

-type f keeps ordinary files, -type d folders, -type l symbolic links. Without -type, find prints everything, the starting folder included. -maxdepth 1 stops find from going below the first level, and -mindepth 1 removes the starting folder from the list.

Terminal window
find . -mindepth 1 -maxdepth 1 -type d
Output
./src
./interdit
./node_modules
./.git

. has disappeared, thanks to -mindepth 1. So has the error message: with -maxdepth 1, find prints ./interdit without opening it, so there is nothing to refuse, and the exit code is 0.

-xdev forbids crossing mount points: a search that starts from / stays on the starting partition. -xtype l keeps the symbolic links whose target does not exist: find . -xtype l prints ./lien-casse.

Filter by permissions and owner

The permissions of a file are written as three digits, one per category: owner, group, others. Each digit adds read (4), write (2) and execute (1); the lesson Linux permissions details this notation. -perm reads in three ways, depending on the sign in front of the value.

NotationFiles keptExample
-perm 600exactly these permissionsonly the files in 600
-perm -644 or -perm -u+xat least these permissions: all those listed, plus possibly others-perm -644 keeps 644, 664 and 755
-perm /111at least one of the permissions listedexecutable by someone
Terminal window
find . -type f -perm 600
find . -type f -perm /111
Output of the first command
find: ‘./interdit’: Permission denied
./app.conf
Output of the second command
find: ‘./interdit’: Permission denied
./run.sh

app.conf is the only file in exactly 600, and run.sh the only file executable by someone. A trap on exact permissions: find . -type f -perm 644 finds several files or none, depending on the umask of the account, which gives 644 or 664 to the files it creates. -perm -644 accepts both. The ! in front of a test reverses its result, and -user NAME keeps the files of an account.

Search by size and understand rounding

-size takes a number followed by a letter that gives the unit: c for bytes, k for kibibytes (KiB), M for mebibytes (MiB) and G for gibibytes (GiB). These units are binary: 1 KiB is 1,024 bytes, 1 MiB 1,048,576 bytes and 1 GiB 1,073,741,824 bytes. M is therefore a little more than a megabyte (1,000,000 bytes).

A + in front of the number means "more than", a - "less than", nothing "equal to", after the rounding described below. With no letter, find counts in blocks of 512 bytes, not in bytes: always write the unit.

find . -type f -size +50k prints ./gros.log, which is 61440 bytes, that is 60 KiB. With c, the comparison is on bytes, with no rounding. With any unit other than c (b, k, M, G), find rounds the file size up to the next unit before comparing, which catches out the first attempt:

Terminal window
find . -type f -size 1k
Output
./src/b.js
./petit-500.bin
./vieux-8j.log
./vieux-7j.log
find: ‘./interdit’: Permission denied
./app.conf
./run.sh
./Report.txt
./rapport.txt
./mon fichier.txt
./node_modules/a.js
./.cache.log
./.git/config

Twelve files come out, including mon fichier.txt, which is 7 bytes: -size 1k does not mean "exactly 1 KiB", it keeps every non-empty file up to 1024 bytes. Empty files are rounded to 0, and -size -1k only keeps those (ancien.tar and vide.txt). For empty files, -empty reads better; to compare without rounding, use bytes: -size -1000c.

Search by modification date

-mtime N counts in 24-hour periods. The age of the file is truncated to whole days: a file modified 7 and a half days ago has age 7. So -mtime +7 means "age strictly greater than 7", that is at least 8 complete 24-hour periods. vieux-7j.log is 180 hours old (7.5 days) and vieux-8j.log 193 hours.

Terminal window
find . -type f -mtime +7
find . -type f -mtime 7
Output of the first command
./vieux-8j.log
find: ‘./interdit’: Permission denied
./ancien.tar
Output of the second command
./vieux-7j.log
find: ‘./interdit’: Permission denied

+7 does not keep vieux-7j.log (age 7, not more than 7), although it is more than 7 days old. ancien.tar, dated 2020, is kept. To keep "more than 7 days", count in minutes: 7 days make 10080 minutes, so -mmin +10080.

To compare with a calendar date, -newermt DATE keeps the files modified after this date (at midnight if only the day is given), and ! -newermt DATE those modified before.

-ctime is not a creation date: it also counts in whole days, but since the last change of the file or of its attributes, and a simple chmod updates it. find 4.10.0 cannot search by creation date on these distributions.

Two roundings not to miss Exercise 1 of 2 · ~8 min · terminal

gros.log is 61440 bytes, exactly 60 KiB. You want to find it with -size, then list the files that are at least 7 whole days old and isolate vieux-8j.log.

Test the 60 KiB limit

Run find . -type f -size 60k, then -size +60k, then -size +59k. Note which ones keep gros.log.

List the files that are at least 7 whole days old

Run find . -type f -mtime +6 and compare with the output of -mtime +7 above: which file is added?

Isolate vieux-8j.log

Write the find command on -mtime that prints only vieux-8j.log.

A hint 1 / 1

For -size, find rounds up to the next unit before comparing. For -mtime, the age is truncated to whole days: work out the age of each file (180 hours, 193 hours).

I have tried: show the solution
Output of -size +60k
find: ‘./interdit’: Permission denied
Output of -size +59k
./gros.log
find: ‘./interdit’: Permission denied
Output of -mtime +6
./vieux-8j.log
./vieux-7j.log
find: ‘./interdit’: Permission denied
./ancien.tar
Terminal window
find . -type f -mtime 8

60k keeps gros.log, +60k keeps none (at least 61 KiB rounded) and +59k keeps it. +6 keeps vieux-7j.log, whose truncated age is 7, which +7 excluded. -mtime 8 keeps an age exactly equal to 8, so vieux-8j.log alone.

Combine criteria: AND, OR and parentheses

Several tests side by side form an AND: the file must pass all of them. -o introduces an OR, but AND takes precedence over OR, and that is the source of a trap. Search for the .log or .txt files that are at least 8 whole days old.

Terminal window
find . -name '*.log' -o -name '*.txt' -mtime +7
Output
./vieux-8j.log
./gros.log
./vieux-7j.log
find: ‘./interdit’: Permission denied
./.cache.log

Four .log files come out, including gros.log and .cache.log, which are recent. find read: "name ending in .log", OR "name ending in .txt AND age greater than 7". The date test only applies to the .txt. For it to apply to both, group with parentheses, protected by backslashes so that the shell does not take them for its own, with spaces around them.

Terminal window
find . \( -name '*.log' -o -name '*.txt' \) -mtime +7
Output
./vieux-8j.log
find: ‘./interdit’: Permission denied

A single file: vieux-8j.log, the only .log or .txt with an age greater than 7. Another rule: the tests are evaluated from left to right, and as soon as you write an action yourself (-print, -exec, -delete), the implicit -print disappears. A test placed after an action no longer filters anything: find . -maxdepth 1 -print -name '*.txt' prints every entry of the first level, because -print comes before -name.

For the same reason, find . -name '*.log' -o -name '*.txt' -print only prints the .txt files: the -print belongs only to the right-hand branch of the -o. Group them: find . \( -name '*.log' -o -name '*.txt' \) -print.

Skip a folder with -prune

In a project, node_modules and .git contain thousands of files that do not interest you. Removing their results with ! -name is not enough, because find goes down into them anyway. -prune tells it not to enter a folder. The construction reads "if the name is node_modules, prune; otherwise (-o), continue with the rest".

Terminal window
find . -name node_modules -prune -o -name '*.js' -print
Output
./src/b.js
find: ‘./interdit’: Permission denied

Only ./src/b.js comes out: node_modules/a.js is not visited. The final -print is necessary: without it, the implicit action applies to everything find keeps, including the pruned folder itself, and ./node_modules is added to the list. To prune two folders, group their names: find . -type d \( -name node_modules -o -name .git \) -prune -o -type f -print.

-prune can also avoid an unreadable folder: find . -name interdit -prune -o -type f -name '*.js' -print prints no message and returns code 0, whereas 2>/dev/null hides the message but leaves the code at 1. Two limits: -prune does not work with -depth (which makes find read the content of a folder before the folder), and -delete turns on -depth by itself, so -prune and -delete cannot be combined.

Act on the files found: -exec, -print0 and -delete

-exec COMMAND {} \; runs the command on each file kept: {} is replaced by its path, and \; marks the end of the command (the ; is protected so that the shell does not interpret it). -exec COMMAND {} + groups the paths to run the command as few times as possible. Compare on the .log files.

Terminal window
find . -type f -name '*.log' -exec echo appel: {} \;
find . -type f -name '*.log' -exec echo appel: {} +
Output with ;
appel: ./vieux-8j.log
appel: ./gros.log
appel: ./vieux-7j.log
find: ‘./interdit’: Permission denied
appel: ./.cache.log
Output with +
find: ‘./interdit’: Permission denied
appel: ./vieux-8j.log ./gros.log ./vieux-7j.log ./.cache.log

With \;, four lines, one per file: echo is run four times. With +, a single line that carries the four paths: echo is run once. In a very large folder, + groups the paths within the limit of the command line size, and the command may be run several times.

File names with spaces

mon fichier.txt contains a space. A list passed to xargs through a pipe splits this name into two words.

Terminal window
find . -name '*.txt' -type f | xargs wc -c
Output
find: ‘./interdit’: Permission denied
15 ./Report.txt
16 ./rapport.txt
wc: ./mon: No such file or directory
wc: fichier.txt: No such file or directory
0 ./vide.txt
31 total

wc looked for two files, ./mon and fichier.txt, and the total only counts three files. The exit code of xargs is 123, which signals that a call failed. For the names to pass intact, find separates the paths with a null byte using -print0 and xargs reads it with -0:

Terminal window
find . -name '*.txt' -type f -print0 | xargs -0 wc -c
Output
find: ‘./interdit’: Permission denied
15 ./Report.txt
16 ./rapport.txt
7 ./mon fichier.txt
0 ./vide.txt
38 total

The whole name is read, and the total goes up to 38. -exec ... {} + also solves the problem, without a pipe.

Delete on a copy, after checking the list

-delete deletes each file kept, with no trash and no confirmation prompt. First write the command with -print, read the list, then replace -print with -delete without touching the rest. Put -delete last: in front of a test, it runs for each file met before the test applies. You work on a copy, and each deletion command carries the full path of the copy, so that find can only touch ~/find-copie.

Terminal window
chmod u+rwx ~/find-lab/interdit
test ! -e ~/find-copie && cp -a ~/find-lab ~/find-copie
chmod 000 ~/find-lab/interdit ~/find-copie/interdit

The first chmod allows cp -a to read interdit, cp -a copies the folder with its dates and permissions, and the last chmod removes the permissions from both interdit folders. The test ! -e avoids creating ~/find-copie/find-lab inside a copy that already exists. List the .log files of the copy, delete them, then list again.

Terminal window
find ~/find-copie -name '*.log' -print
find ~/find-copie -name '*.log' -delete
find ~/find-copie -name '*.log' -print

The first command prints the four .log files, each preceded by the full path of the copy, plus a Permission denied message about interdit. The second prints only this message: -delete deletes without writing anything. The third proves it, because no .log comes out any more. A silent -delete is not a -delete that failed: always check with the first command.

Delete the .js files except those in node_modules Exercise 2 of 2 · ~8 min · terminal

In ~/find-copie, you want to delete the .js files without entering node_modules. You write find ~/find-copie -name node_modules -prune -o -name '*.js' -delete. Proceed in this order: try, list, delete, check.

Try the command

Run it, then echo $? right after. Read the message and note the code.

List what is targeted

Replace -delete with -print to see what the command was aiming at.

Delete, then check

Write the command that really deletes src/b.js while keeping node_modules intact, then run find ~/find-copie -name '*.js' again.

A hint 1 / 1

-delete is not the only action that deletes: another one runs a command, and it does not turn on -depth.

I have tried: show the solution
Output with -delete
find: The -delete action automatically turns on -depth, but -prune does nothing when -depth is in effect. If you want to carry on anyway, just explicitly use the -depth option.
Terminal window
find ~/find-copie -name node_modules -prune -o -name '*.js' -print
find ~/find-copie -name node_modules -prune -o -name '*.js' -exec rm {} +
find ~/find-copie -name '*.js'

The first command refuses to run and returns code 1: with -depth, -prune no longer protects node_modules. The message suggests adding -depth, but node_modules/a.js would then be deleted with the rest. The list with -print only targets src/b.js. With -exec rm {} +, -prune keeps its effect: src/b.js disappears and the last command only prints node_modules/a.js (with the full path of the copy), plus the message about interdit.

Which command should I use?

To find a syntax quickly, start from the need.

NeedCommand
Run a command from the folder of each filefind . -name 'b.js' -execdir echo {} \;
Files of another accountfind . -type f -user root
Files that others cannot readfind . -maxdepth 1 -type f ! -perm -o=r
Files modified since a datefind . -type f -newermt 2020-01-02
Broken symbolic linksfind . -xtype l

-execdir runs the command from the folder of the file, with ./b.js instead of ./src/b.js: the GNU findutils manual recommends it for security reasons.

Troubleshooting

When find does not return what you expect, first read the error message and the exit code (echo $? right after the command). According to the find manual page, the code is 0 if all the files were processed without error, and greater than 0 if an error occurred: it does not tell whether find found anything.

SymptomCauseFix
find: ‘./interdit’: Permission denied, code 1, although files are printedThe account cannot open this folderls -ld interdit, then -prune to avoid it or grant access if that is legitimate. 2>/dev/null hides the message without changing the code
No result although the file existsCase of the name, pattern without quotes (paths must precede expression), unreadable folder-iname, single quotes, Permission denied message
The -delete action automatically turns on -depth, but -prune does nothing-delete and -prune cannot be combined-print to list, then -exec rm {} + with -prune, or precise names
wc: ./mon: No such file or directory, code 123 for xargsA name contains a space and xargs split it-print0 with xargs -0, or -exec ... {} +
-perm 644 or -mtime +7 misses a fileFiles in 664 depending on the umask, age truncated to whole days-perm -644, -mmin +10080

Clean up the practice folder

When you are done, delete the practice folders. interdit has no permission: give it its permissions back first, otherwise find cannot empty it. First run the list with -print: it must only show paths under ~/find-lab, ~/find-copie and ~/find-carte.

Terminal window
chmod -R u+rwx ~/find-lab ~/find-copie ~/find-carte
find ~/find-lab ~/find-copie ~/find-carte -print
find ~/find-lab ~/find-copie ~/find-carte -delete

The three folders disappear with their content. This command touches nothing else; if you did not create one of them, chmod and find only report that it does not exist.

The find Shorts on video

Explanations from this guide also exist as YouTube Shorts. Each video has two audio tracks, one in English and one in French: pick the language in the player settings.

Key points

  • find START OPTIONS TESTS ACTION evaluates from left to right. With no action, find adds -print; an action you write removes it, and a test placed after -print or -delete no longer filters anything.
  • The pattern of -name goes between single quotes. -size rounds up except in c, -mtime +7 keeps the files that are at least 8 whole days old (-mmin +10080 for "more than 7 days"), -ctime is not a creation date.
  • An empty result with Permission denied does not prove the file is absent, and the exit code is 1.
  • AND takes precedence over OR: group with \( ... -o ... \). -prune -o ... -print avoids entering a folder, but cannot be combined with -depth or -delete.
  • -exec ... {} + makes as few calls as possible, -print0 with xargs -0 passes names with spaces. Before -delete, run the same command with -print, with the full path of a copy.

Knowledge check

Check that you have the essentials of this guide. The questions cover only what was explained here.

Knowledge check

Check what you have learned with this interactive quiz

6 questions
6 min
70% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer

FAQ - Frequently Asked Questions