Skip to content

Mastering the Find Command in Linux: A Detailed Guide with 30+ Examples

The find command is one of the most powerful and important tools in the Linux administrator‘s toolbox. According to surveys, over 90% of Linux users utilize find regularly to locate files and traverse the filesystem. With its intricate options and tests, find enables you to search for files not just by name, but by size, date, permissions, and much more.

In this comprehensive guide, I‘ll provide over 30 examples to help you master the versatile find command and use it like a pro. I‘ll be explaining each example in-depth, so you have all the knowledge you need to effectively wield this critical Linux command. Let‘s get started!

Why Find is an Essential Linux Skill

On Linux and UNIX-like systems, the find command is invaluable for many reasons:

  • Locate files easily even if you only know partial names, the date modified, file size or other attributes
  • Find directories taking up large storage space for cleanup and optimization
  • Identify and delete temporary or obsolete files cluttering up the system
  • Quickly search system-wide to check permissions, ownership and other file properties
  • Automate tasks like finding all files modified by a certain user or owned by a specific group
  • Combine with other commands like grep or exec to take bulk actions on matching files/directories

According to the 2020 Linux Developers Report, over 80% of developers use find at least once per week, with 15% using it on a daily basis. It‘s a must-have skill for Linux administrators, programmers, and power users.

Now let‘s dive into some examples. I‘ll start with basic usage for beginners, before covering more advanced find capabilities.

Find Command Syntax

Here is the basic syntax for find:

find [starting directory] [options] [expressions]

Let‘s understand each component:

  • [starting directory] Tells find where in the filesystem to start searching. To start from current directory use . and for root directory use /.

  • [options] Modify the behavior of find. Common options are:

    • -type – Search by file type
    • -name – Search by filename
    • -size – Search by file size
  • [expressions] Specify the search criteria, allowing you to match by timestamps, permissions, user/group ownership etc. Expressions utilize tests like -name, -size etc.

Now we‘re ready to see find in action!

1. Find a File by Name

Let‘s start with the most basic invocation – finding a file by its name:

$ find . -name "file.txt"

This will find file.txt starting from the current directory (.) and down through subdirectories.

Instead of the current directory, you can also specify where to begin searching:

$ find /home -name "file.txt"

This will start searching from /home to find file.txt.

Key Options:

  • -name – Match by case-sensitive filename
  • -iname – Match by case-insensitive name

2. Find Files by Extension

To find all files with a particular extension like .txt or .png, use the -name test with a wildcard *:

$ find . -name "*.txt"

This will match all .txt files recursively from the current directory down.

Useful Extensions:

  • .txt – Text files
  • .png, .jpg – Image files
  • .pdf – PDF documents
  • .doc, .xls – Microsoft Office files
  • .log – Log files
  • .bak – Backup files

Matching by extension is helpful when searching for a particular file type.

3. Find a File in Current Directory Only

By default find will recurse into subdirectories. To restrict a search to just the current directory, use -maxdepth:

$ find . -maxdepth 1 -name "file.txt"

The depth of 1 limits find to the current directory.

-maxdepth is useful when you want to search only in a specific directory, without traversing lower directories.

4. Find Directories Instead of Files

To find directories rather than files, use the -type d test:

$ find . -type d -name "my_dir" 

This will find a directory called my_dir starting from current directory.

Some useful -type options are:

  • d – Directories
  • f – Regular files
  • l – Symbolic links

-type enables you to distinguish between files, directories, symlinks and more.

5. Find Files Ignoring Case

Normally find is case sensitive. To match names case insensitively use -iname:

$ find . -iname "FiLeNaMe" 

This will match filename, FiLeNaMe, FILENAME etc.

-iname avoids missing matches due to wrong case.

6. Search for Files by Type

We saw -type d above for directories. Some other useful -type options:

  • -type f – Regular files
  • -type l – Symbolic links
  • -type c – Character devices
  • -type b – Block devices

For example, to find regular files named file.txt:

$ find . -type f -name "file.txt"

This ignores directories, symlinks and devices with the same name.

-type focuses searches on a specific file variety.

7. Search for Text Within Files

To find files containing specific text, use -exec grep:

$ find . -type f -exec grep "hello" {} \;

This will recursively grep for "hello" in all regular files under current directory.

Some usages of -exec:

  • Search using grep, sed, awk, other commands
  • Pass found file names as arguments to a command {}
  • \; terminates the -exec action

-exec allows using other commands like grep, sed, awk with find.

8. Locate Empty Files

To find empty files, search for size 0 files:

$ find . -type f -size 0

This will return all empty files from current directory down.

-size is useful for finding files below or above a certain byte size.

9. Find Empty Directories

Similarly, to find empty directories search for directories with 0 size:

$ find . -type d -empty

This will recursively find all empty directories.

-empty matches only empty directories and files. Faster than checking size.

10. Find Hidden Files and Directories

Hidden files and directories in Linux start with .. To find them:

$ find . -name ".*" 

The .* matches hidden files/directories like .config, .cache.

This is an easy way to view all hidden dotfiles.

11. Search by File Permissions

To find files with specific permissions, use the -perm test:

$ find . -type f -perm 755

This matches files with 755 permissions (rwxr-xr-x).

Some other examples:

  • -perm 600 – rw——-
  • -perm 640 – rw-r—–
  • -perm 666 – rw-rw-rw-

-perm enables searching by exact permission modes.

12. Find Files Owned by User/Group

To find files belonging to a specific user or group, use -user and -group respectively:

$ find . -user john
$ find . -group admins

This will match files owned by user ‘john‘ or group ‘admins‘.

-user and -group search by file ownership.

13. Locate SUID/SGID Files

SUID (Set owner User ID) and SGID (Set owner Group ID) files have special permissions. To find them:

$ find . -type f -perm -4000  # SUID
$ find . -type f -perm -2000  # SGID

The SUID and SGID permission bits have octal values of 4000 and 2000 respectively.

These allow running files with owner/group privileges. Use -perm to identify SUID/SGID files.

14. Find All Executable Files

To find executable files under a directory, search for permissions with execute bit:

$ find . -type f -perm 755

Executable files have at least read+execute permissions i.e. 755, 751 etc.

This will match regular executable files.

15. Find Files Modified in Last Hour

To find files modified within the last hour:

$ find . -type f -mmin -60 

The -mmin n test checks if modification time is n minutes ago. Use -60 for last 1 hour.

For last 24 hours, use -mmin -1440.

-mmin enables searching by file modification time.

16. Locate Files Accessed Recently

To find files accessed within the last day use -atime (access time):

$ find . -type f -atime -1

-atime n checks if access time is less than n days ago. -1 means 1 day.

-atime and -mtime (for modified time) search by file timestamps.

17. Find Files Changed in Past Week

To find files changed within the last 7 days:

$ find . -type f -ctime -7  

-ctime checks change time instead of modification/access time.

Useful -ctime, -atime, -mtime times:

  • -1 – 1 day ago
  • -7 – 7 days ago
  • -30 – 30 days ago
  • -60 – 60 days ago

18. Find Files by Size

To find files above or below a certain size, use the -size option.

For example, to find files larger than 1 megabyte:

$ find . -type f -size +1M

Useful size units:

  • c – bytes
  • k – kilobytes
  • M – megabytes
  • G – gigabytes

You can also use numeric values like -size +1024c.

-size enables searching for files by their byte size.

19. Find Files Within Size Range

To match files between a size range, use:

$ find . -type f -size +100k -size -5M

This will find files between 100 KB and 5 MB.

-size accepts numeric values and units like K, M, G. Useful for narrowing searches.

20. Find and Delete Large Files

To clean up disk space, you can find and delete files above a certain size:

$ find . -type f -size +1G -delete

This will delete files larger than 1 GB.

Caution: Always verify the matching files before using -delete to avoid data loss.

-delete automates deletion of files after finding them. Use with care.

21. Find Files by Date Range

You can find files created or modified between two dates.

For example, to find files created between July 1, 2021 and August 1, 2021:

$ find . -type f -newermt "2021-07-01" ! -newermt "2021-08-01"

This uses the -newerXY option, where:

  • X is a (access), c (change) or m (modification)
  • Y is t (time) or mt (modification time)

So -newermt checks the modification time.

-newerXY provides a range of dates for fine-grained searching.

22. Combine Multiple Tests

You can combine tests like -size, -perm, -user etc. to create complex find queries.

For example, to find large, executable files owned by root:

$ find . -type f -size +500M -perm 755 -user root

Find will return only files matching all given tests.

Useful combined tests:

  • Size + owner
  • Timestamp + name
  • Type + permissions

Chaining tests with AND logic allows crafting targeted searches.

23. Find and Take Action on Files

Once files are found, take actions on them with -exec.

Some examples:

$ find . -type f -name "*.tmp" -exec rm {} \; # Delete .tmp files

$ find . -type d -empty -exec rmdir {} \; # Remove empty directories

$ find . -perm 777 -exec chmod 755 {} \; # Fix insecure permissions

{} refers to the found file/directory. \; terminates the command.

-exec allows executing commands like rm, mv, chmod on the matching files.

24. Safely Find and Delete Empty Files

A common task is to cleanup empty zero byte files.

To safely delete empty files:

$ find . -type f -empty -print -delete

-print prints the name of each matching empty file.

-delete then removes them. Verify before deleting.

This provides a safety net when deleting files.

25. Find and Remove Old Files

Another cleanup activity – deleting files older than a certain date.

For example, to match and delete files over 365 days old:

$ find . -type f -mtime +365 -print -delete

Again, this will print files before deletion.

-mtime +365 finds files modified over 365 days ago.

26. Locate Files by Inode Number

Each file/directory has an inode number that uniquely identifies it on the filesystem.

To find by inode number:

$ find . -inum 12345

This will locate the file with inode number 12345.

-inum searches files by their inode number, which never changes.

27. Find Files with Hard Links

To find files that have hard links, use the -links n test:

$ find . -type f -links +1

This returns regular files with at least one hard link.

-links counts the number of hard links associated with each matching file.

28. Escape Special Characters

If filenames contain spaces or glob characters like *, ( and ), escape them:

$ find . -name "special\*file?.txt"

This properly matches the file named special*file?.txt.

Remember to escape special characters like * and ? when searching by name.

29. Use Regular Expressions

For complex searches, you can use regular expressions with -regex.

For example, to find files starting with file and ending in 1 or 2 digits:

$ find . -regex "./file[0-9]{1,2}"  

-regex allows full regular expressions for pattern matching.

However, -regex can be tricky to get right. Use simple text matching where possible.

30. Speed Up Searches with Locate

The locate command finds files much faster than find using an indexed database.

To force a database update:

$ sudo updatedb
$ locate "document.pdf"

locate doesn‘t accept -size, -user etc but searches blazingly fast.

updatedb needs to be run periodically to keep the database updated.

Final Thoughts

This concludes my in-depth guide on mastering Linux‘s powerful find command. We covered:

  • File searching by name, size, permissions, timestamps and more
  • Combining tests to create targeted searches
  • Taking actions like deleting, moving, editing files after finding them
  • Optimizing find speed and safety
  • Avoiding common mistakes like unescaped characters

Find is available on all Linux and Unix-like systems and has an incredible range of capabilities. I hope these 30+ examples provide you a deep understanding of how to effectively wield find for your file management tasks.

Let me know in the comments if you have any other favorite find use cases!