Learn / Linux / Getting Started
Lesson 8 of 74

Finding Files

Find anything on a server. find by name, type, size, age, owner and permissions, combining conditions, acting on results with -exec and -delete, searching inside files with grep -r, and locating commands with which, type and whereis.

25 min read Report a problem Hands-on lab included 6-question quiz
You know...UseExample question
something about the file: name, type, size, age, owner, permissionsfind"Where is nginx.conf? Which files are over 1 GB? What changed in the last hour?"
something inside the file: a word, a setting, an error messagegrep -r"Which config file sets db_host?"
the name of a commandwhich, type, whereis"Which python3 runs when I type it?"

find: how it works

find walks through a directory tree, folder by folder, checks every file and folder against your conditions, and does something with each match: by default, print its path.

The shape of every find command

findthe command
/var/logwhere: one or more starting folders
(default: the current folder)
-name "*.log" -size +100Mconditions ("tests")
all must be true
-deleteaction
(default: print the path)

find /var/log -name "*.log" -size +100M -delete → delete every .log file over 100 MB under /var/log.

Unlike most commands, find's options are words with a single dash (-name, -type), and their order matters: find reads them left to right.

Finding by name

TestMatches
-name "app.log"exactly app.log
-name "*.log"anything ending in .log (*, ? and [...] wildcards work)
-iname "readme*"case-insensitive: README.md, readme.txt, ReadMe
-path "*/nginx/*.conf"matches against the whole path, not only the name
bash
find /srv/projects -name "payments.yaml"
find /srv/projects -iname "payments.yaml"
text
/srv/projects/shop/services/payments/config/Payments.yaml

The first command printed nothing: no match, and no error either. The file is called Payments.yaml with a capital P, and -name is case-sensitive. -iname found it.

Forgetting the quotes: find . -name *.log. If the current folder happens to contain app.log, the shell expands *.log to app.log before find runs, and find then searches only for files called exactly app.log. It "works" in one folder and silently misses files in another. Always quote patterns: -name "*.log".

Try it · Task 1 of 4

Find by name

Locate the payments service's config file and save its full path.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

-name matches file names exactly as you write them, wildcards included. Always quote the pattern ("*.yaml"), so the shell passes it to find instead of expanding it itself. And remember Linux is case-sensitive: -name won't match Payments.yaml if you type payments.yaml. That's what -iname (case-insensitive) is for.

1. Search by exact name

bash
find /srv/projects -name "payments.yaml"
PartMeaning
findsearch a directory tree
/srv/projectswhere to start; find goes into every subfolder
-name "payments.yaml"match files with exactly this name
text
(no output)

Nothing. No error either, just no match. Someone saved the file with a capital letter.

2. Ignore upper and lower case

bash
find /srv/projects -iname "payments.yaml"

What -iname does: the same as -name, but Payments.yaml, PAYMENTS.YAML and payments.yaml all match.

text
/srv/projects/shop/services/payments/config/Payments.yaml

Found: one line per match, with the full path.

3. Wildcards and types

bash
find /srv/projects -iname "*payments*"
find /srv/projects/shop -maxdepth 2 -type d
PartMeaning
"*payments*"any name containing "payments"
-maxdepth 2go at most 2 levels below the starting folder
-type donly directories. -type f means regular files, -type l links.
text
/srv/projects/shop/services/payments
/srv/projects/shop/services/payments/config/Payments.yaml
/srv/projects/shop/docs/payments-guide.md
text
/srv/projects/shop
/srv/projects/shop/services
/srv/projects/shop/services/catalog
...
/srv/projects/shop/docs

The first search matched a folder and two files. Add -type f to keep only files.

2 · Your task

Find the payments service's config file (named payments.yaml, in any upper/lower case) under /srv/projects, and save its full path to /root/payments-config.txt.

Expected result: cat /root/payments-config.txt prints one full path ending in .yaml.

Hint: the commands, explained
text
find /srv/projects -iname "payments.yaml" > /root/payments-config.txt

What each part does

  • find /srv/projects: search this folder and every folder below it.
  • -iname "payments.yaml": match the file name, ignoring upper/lower case. The quotes stop the shell from expanding anything first.
  • > FILE saves the full paths found.
First start the lab machine in the terminal panel on the right.

Finding by type

TestMatches
-type fregular files
-type ddirectories
-type lsymbolic links
text
find /etc -type d -name "*nginx*"      # folders with nginx in the name
find /home -type f -name "*.sh"        # shell scripts in users' homes

Limiting the depth

By default, find goes all the way down. -maxdepth N stops it after N levels (put it right after the starting folder):

bash
find /srv/projects/shop -maxdepth 2 -type d
text
/srv/projects/shop
/srv/projects/shop/services
/srv/projects/shop/services/catalog
/srv/projects/shop/services/users
/srv/projects/shop/services/search
/srv/projects/shop/services/cart
/srv/projects/shop/services/payments
/srv/projects/shop/docs

The starting folder is depth 0, its children depth 1 (services, docs), and their children depth 2. Anything deeper is skipped. -mindepth 1 would leave out the starting folder itself.

Finding by size

-size takes a number and a unit, with a sign that matters:

TestMatches
-size +100Mmore than 100 megabytes
-size -10kless than 10 kilobytes
-size +1Gmore than 1 gigabyte
-emptyempty files (and empty folders)

Units: k kilobytes, M megabytes, G gigabytes (and c for bytes). Without a sign, -size 100M means "exactly 100 MB, rounded up", which is almost never what you want.

bash
find /srv/media -type f -size +100M -exec ls -lh {} +
text
-rw-r--r-- 1 root root 750M Nov 24 15:21 /srv/media/backups/db-dump-old.sql
-rw-r--r-- 1 root root 120M Nov 24 15:21 /srv/media/uploads/promo-video.mp4

Only two files over 100 MB, and an old database dump is the biggest. This exact command is one of the first things to run when a disk fills up. (The -exec part is explained below.)

Try it · Task 2 of 4

Find big files

List every file larger than 100 MB under /srv/media.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

When a disk fills up, the first question is "what's big?". -size filters by size: +100M means more than 100 megabytes, -1k means less than 1 kilobyte. Units: k (kilobytes), M (megabytes), G (gigabytes).

1. Files larger than 100 MB

bash
find /srv/media -type f -size +100M
PartMeaning
/srv/mediawhere to look
-type fregular files only
-size +100Mlarger than 100 MB
text
/srv/media/backups/db-dump-old.sql
/srv/media/uploads/promo-video.mp4

Two files out of more than thirty. Only the paths are shown, so we don't know their sizes yet.

2. Show details with -exec

bash
find /srv/media -type f -size +100M -exec ls -lh {} +
PartMeaning
-exec ls -lh {} +run ls -lh on the results. {} is replaced by the found files, and + passes them all in one go.
text
-rw-r--r-- 1 root root 750M Nov 24 15:21 /srv/media/backups/db-dump-old.sql
-rw-r--r-- 1 root root 120M Nov 24 15:21 /srv/media/uploads/promo-video.mp4

An old 750 MB database dump is the biggest offender: a typical finding during a "disk full" incident.

2 · Your task

Save the list of all files larger than 100 MB under /srv/media (paths only, one per line) to /root/big-files.txt.

Expected result: /root/big-files.txt lists exactly the two big files.

Hint: the commands, explained
text
find /srv/media -type f -size +100M > /root/big-files.txt

What each part does

  • -type f: regular files only (not folders).
  • -size +100M: bigger than 100 megabytes (- would mean smaller, k/G other units).
First start the lab machine in the terminal panel on the right.

Finding by age

Every file has timestamps (you saw them with stat). find can test them:

TestCounts inMatches files whose...
-mtime +30dayscontents were modified more than 30 days ago
-mtime -1dayscontents were modified in the last 24 hours
-mmin -60minutescontents were modified in the last 60 minutes
-newer ref.txtwere modified more recently than ref.txt
-atime / -aminwere last accessed (read)
-ctime / -cminhad their metadata changed (permissions, owner)

Reading -mtime

-mtime +30older than 30 days
"clean these up"
30 days ago
(neither)between 7 and 30 days
7 days ago
-mtime -7changed in the last 7 days
"what's new?"
now
bash
find /var/log/shopapp/archive -name "*.log" -mtime +30
text
/var/log/shopapp/archive/app-2026-09-15.log
/var/log/shopapp/archive/app-2026-08-21.log
/var/log/shopapp/archive/app-2026-10-10.log

The three logs older than 30 days. Notice they're not sorted: find prints files in the order it meets them on disk. Pipe through sort if order matters.

Two everyday uses:

text
find /etc -mmin -30                     # what config changed in the last 30 minutes? (incident!)
find /var/www -newer /tmp/deploy-start  # what did the deployment change?

Finding by owner and permissions

TestMatches
-user adityafiles owned by the user aditya
-group www-datafiles belonging to the group www-data
-nouserfiles whose owner no longer exists (left over after deleting a user)
-perm 777permissions exactly 777
-perm -o+wfiles that everyone can write to, a security check

You'll understand these fully after the permissions lessons. For now, know they exist: security audits run things like find / -type f -perm -o+w 2>/dev/null.

Combining conditions

Several conditions in a row must all be true (AND):

text
find /var/log -type f -name "*.log" -size +50M -mtime +7

For OR, use -o, and group with escaped parentheses \( \). For NOT, use !:

bash
find /srv/projects \( -name "*.yaml" -o -name "*.md" \) -type f
PartMeaning
\( ... \)group conditions. The backslashes stop the shell from treating the brackets specially. Spaces around them are required.
-name "*.yaml" -o -name "*.md"name ends in .yaml or .md
-type fand it's a regular file
text
/srv/projects/shop/services/catalog/config/service.yaml
/srv/projects/shop/services/users/config/service.yaml
...
/srv/projects/shop/services/payments/config/Payments.yaml
/srv/projects/shop/docs/payments-guide.md
text
find /srv/projects -type f ! -name "*.py"     # every file that is NOT a .py file

Acting on what you find

By default find prints paths. Actions let it do more:

ActionDoes
-printprint the path (the default)
-lsprint details like ls -l
-deletedelete each match. Must come last.
-exec CMD {} \;run CMD once per file; {} is replaced by the file's path
-exec CMD {} +run CMD once with many files at a time (much faster)
-ok CMD {} \;like -exec, but asks for confirmation for each file
text
find /var/log -name "*.log" -size +100M -exec ls -lh {} +      # show details
find /srv/app -type f -name "*.sh" -exec chmod +x {} +         # make all scripts executable
find /tmp -type f -mtime +7 -delete                            # delete week-old temp files
find . -name "*.conf" -exec grep -l "8080" {} +                # which .conf files mention 8080?

Delete safely: preview, then delete

-delete and -exec rm have no undo. Use the same two-step routine as with rm:

  1. Run the command without the action. Read the list carefully.
  2. Press ↑ and add -delete at the end.

Putting -delete first: find /data -delete -name "*.tmp". find evaluates left to right, so it deletes everything under /data before even looking at the name. -delete always goes last.

Hiding "Permission denied"

Searching the whole system as a normal user produces pages of errors from folders you can't read. Send the errors to /dev/null:

text
find / -name "*.pem" 2>/dev/null

2> redirects error messages. You'll learn exactly how in the redirection lesson.

Try it · Task 3 of 4

Find old files and clean up

Delete the archived logs older than 30 days, and keep the newer ones.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

-mtime filters by when a file's contents were last modified, in days: +30 means more than 30 days ago, -7 means within the last 7 days. Cleaning up old logs and backups this way is one of the most common jobs on servers, usually run from cron every night.

Deleting with find follows the same rule as rm: preview first, then delete.

1. Look at what's there

bash
ls -l /var/log/shopapp/archive
text
-rw-r--r-- 1 root root 21 Aug 21 15:21 app-2026-08-21.log
-rw-r--r-- 1 root root 21 Sep 15 15:21 app-2026-09-15.log
-rw-r--r-- 1 root root 21 Oct 10 15:21 app-2026-10-10.log
-rw-r--r-- 1 root root 21 Nov  4 15:21 app-2026-11-04.log
-rw-r--r-- 1 root root 21 Nov 14 15:21 app-2026-11-14.log
-rw-r--r-- 1 root root 11 Nov 23 15:21 app-recent-1.log
-rw-r--r-- 1 root root 11 Nov 22 15:21 app-recent-2.log
-rw-r--r-- 1 root root 11 Nov 21 15:21 app-recent-3.log

Eight logs of different ages. (Your dates are relative to today, so they'll differ.)

2. Preview: which are older than 30 days?

bash
find /var/log/shopapp/archive -name "*.log" -mtime +30
PartMeaning
-name "*.log"only log files
-mtime +30last modified more than 30 days ago
text
/var/log/shopapp/archive/app-2026-09-15.log
/var/log/shopapp/archive/app-2026-08-21.log
/var/log/shopapp/archive/app-2026-10-10.log

Three files, in no particular order (find lists them in the order it meets them on disk). The 20-day-old and 10-day-old logs and the recent ones are not in the list. Good: those must stay.

3. Delete exactly those

bash
find /var/log/shopapp/archive -name "*.log" -mtime +30 -delete

What -delete does: deletes every file that matched. It must come last: find reads conditions left to right, and -delete placed before -name would delete everything it walks past.

Check: ls -l /var/log/shopapp/archive should now show five files.

2 · Your task

Delete every .log file in /var/log/shopapp/archive that is older than 30 days. Keep all the newer ones.

Expected result: the three old logs are gone, and the five newer ones are still there.

Hint: the commands, explained
text
find /var/log/shopapp/archive -name "*.log" -mtime +30
find /var/log/shopapp/archive -name "*.log" -mtime +30 -delete

What each part does

  • -name "*.log" -mtime +30: .log files last modified more than 30 days ago.
  • Run it once without -delete to check exactly what matches.
  • Then add -delete to remove those files. Always preview first: deleted files are gone for good.
First start the lab machine in the terminal panel on the right.

Searching inside files: grep -r

find never opens files. To search their contents, use grep with -r (recursive):

bash
grep -r "db_host" /etc/shopapp
text
/etc/shopapp/conf.d/30-storage.conf:db_host=pg-prod-7.internal

Each result is file name, a colon, and the matching line.

OptionEffect
-rsearch all files in the folder tree
-lprint only the names of files that match
-nadd line numbers
-iignore upper/lower case
-wmatch whole words only (port won't match export)
--include="*.conf"only search files matching a pattern
--exclude-dir=.gitskip a folder
bash
grep -rni --include="*.conf" "DB_HOST" /etc/shopapp
text
/etc/shopapp/conf.d/30-storage.conf:1:db_host=pg-prod-7.internal

File, line number, line: found despite searching in capitals. grep gets its own full lesson in the text processing module.

Try it · Task 4 of 4

Search inside files

Find which config file sets the database host, and save the host name.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

find looks at file names and properties. To search inside files, use grep -r: it reads every file in a folder tree and prints the lines that contain your text, with the file name in front. It's how you answer "which config file sets this?" on a server with hundreds of config files.

1. Search a folder tree

bash
grep -r "db_host" /etc/shopapp
PartMeaning
grepsearch for text
-rrecursive: every file in the folder and its subfolders
"db_host"the text to look for
/etc/shopappwhere to search
text
/etc/shopapp/conf.d/30-storage.conf:db_host=pg-prod-7.internal

The format is file name, a colon, then the matching line. The database host is set in 30-storage.conf.

2. Useful variations

CommandWhat it shows
grep -rl "db_host" /etc/shopapponly the file names (-l), no lines
grep -rn "db_host" /etc/shopappadds the line number
grep -ri "DB_HOST" /etc/shopappignores upper/lower case (-i)
grep -r --include="*.conf" "db_host" /etconly searches .conf files
text
$ grep -rni --include="*.conf" "DB_HOST" /etc/shopapp
/etc/shopapp/conf.d/30-storage.conf:1:db_host=pg-prod-7.internal

File, line number 1, and the line, found even though we searched in capitals.

3. Where is a command?

bash
which python3
which shopctl; echo "exit code: $?"
find / -name shopctl -type f 2>/dev/null
CommandWhat it does
which python3shows the program that runs when you type python3, searched through PATH
which shopctlprints nothing and returns exit code 1: not found in PATH
find / -name shopctl ... 2>/dev/nullsearch the whole system. 2>/dev/null hides "Permission denied" noise from /proc.
text
/usr/bin/python3
exit code: 1
/opt/shopapp/bin/shopctl

shopctl exists, but in /opt/shopapp/bin, which isn't in PATH. That's why typing shopctl would say "command not found".

2 · Your task

Find which file under /etc/shopapp sets db_host, and save just the host name (the value after =) to /root/db-host.txt.

Expected result: cat /root/db-host.txt prints the database host name.

Hint: the commands, explained
text
grep -r "db_host" /etc/shopapp
echo pg-example.internal > /root/db-host.txt

(with the real host name).

What each part does

  • grep -r "db_host" /etc/shopapp: search inside every file under this folder (recursive) and print each matching line with its file name.
  • Read the value from the output, then save it with echo VALUE > /root/db-host.txt.
First start the lab machine in the terminal panel on the right.

Finding commands: which, type, whereis

CommandTells you
which python3the program that runs when you type python3 (searched through PATH)
type python3 cdwhat each name is: a program, a shell builtin, an alias or a function
whereis python3the program, its man page and related files
command -v python3like which, but built into the shell, best for scripts
bash
which python3
type python3 cd
whereis python3
text
/usr/bin/python3
python3 is /usr/bin/python3
cd is a shell builtin
python3: /usr/bin/python3 /usr/lib/python3 /etc/python3 /usr/share/python3 /usr/share/man/man1/python3.1.gz

When which prints nothing, the command isn't in PATH. It may not be installed at all, or it lives somewhere like /opt/app/bin. find / -name NAME -type f 2>/dev/null finds it either way.

locate: fast, but not always there

locate nginx.conf searches a pre-built database of file names, so it's instant even on huge disks. The catch: the database is updated once a day (or by running updatedb), so brand-new files are missing, and many servers don't have it installed (apt install plocate). find is slower but always current and always available.

"How do you find all files larger than 1 GB?" find / -type f -size +1G 2>/dev/null, adding -exec ls -lh {} + to see their sizes.

"How do you delete log files older than 30 days?" find /var/log/app -name "*.log" -mtime +30 -delete, after previewing without -delete. In practice this runs from cron or is handled by logrotate.

"How do you find which files changed in the last hour?" find /path -mmin -60.

"What's the difference between find and grep?" find searches file names and properties; grep searches the text inside files.

Summary

  • find WHERE CONDITIONS ACTION; conditions are read left to right and all must match.
  • Name: -name "*.log" (quoted!), -iname ignores case. Type: -type f/d/l. Depth: -maxdepth N.
  • Size: -size +100M. Age: -mtime +30 (older), -mtime -7 (newer), -mmin -60, -newer FILE.
  • Owner and permissions: -user, -group, -perm. Combine with -o, ! and \( \).
  • Actions: -exec CMD {} +, -delete (always last, preview first). Hide errors with 2>/dev/null.
  • grep -r TEXT DIR searches inside files (-l, -n, -i, --include).
  • which, type, whereis, command -v locate commands.
Check your understanding

Quick quiz

Feedback