Skip to content

Linux Foundations / Find your way around Linux ยท Step 25 of 63

Lesson: findSwitch
โ† Linux Foundations

Shell and files

find

Search directory trees for files by name, type, size and age with find.

find searches a directory tree for files that match conditions you give. The usual shape is: find WHERE CONDITIONS.

Searching by name

$ find /home/pete -name "notes.txt"
/home/pete/Documents/notes.txt

find looks in the starting directory and every directory below it. Use . to start where you are. Quote patterns containing wildcards, so the shell passes them to find unchanged:

$ find . -name "*.log"
./app.log
./logs/error.log

-name is case sensitive. -iname ignores case.

Filtering by type, size and time

  • -type f matches regular files and -type d matches directories.
  • -size +10M matches files larger than 10 MiB.
  • -mtime -7 matches files modified within the last seven days.
  • -empty matches empty files and directories.

Conditions listed together must all be true:

$ find /var/log -type f -name "*.gz"
/var/log/dpkg.log.2.gz

For numbers, + means more than and - means less than. Sizes are rounded up to whole units before comparing, so check results near a boundary.

Limiting depth and errors

-maxdepth 1 stays in the starting directory only. Put it before the other conditions.

Searching system directories as a normal user often prints Permission denied. You can discard error messages with 2>/dev/null:

$ find /etc -name "*.conf" 2>/dev/null

Acting on results

-exec runs a command on each match. {} stands for the file name and \; ends the command:

$ find . -name "*.log" -exec ls -l {} \;

GNU and BSD find also support -delete. It is permanent, so run the search without it first and read the list. Place -delete at the end: if it comes before your conditions, it can remove far more than you meant.

Practise in the search and archives lab.

Try it

  1. Run find . -type d in your home directory.
  2. Search /etc for names ending in .conf.
  3. Find files changed in the last day with -mtime -1.
  4. Add -exec ls -lh {} \; to one of your searches.

Check your understanding

find

All 5 sections ยท no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.