Commands

Find Command on Linux with Examples

Find Command on Linux

In the vast landscape of Linux file systems, locating specific files can feel like searching for a needle in a haystack. Whether you’re a system administrator managing thousands of files across multiple directories or a regular user trying to locate that one important document, the Linux find command stands as an indispensable tool in your arsenal. This powerful utility allows you to search through the filesystem hierarchy, locate files based on numerous criteria, and even execute operations on the files you find.

Understanding the Find Command

The find command is one of the most versatile utilities in Linux, designed specifically for searching files and directories within a specified hierarchy. Unlike simpler tools, find offers granular control over search parameters, allowing you to locate files based on names, types, sizes, modification times, permissions, and much more.

The basic syntax of the find command follows this structure:

find [path] [options] [expression]

Where:

  • [path] is the directory where find begins its search
  • [options] modify how find behaves
  • [expression] defines the search criteria

By default, if you run find without any options, it will recursively list all files and directories starting from the current directory. The command traverses directory structures depth-first, examining every file and subdirectory unless instructed otherwise.

Basic Find Command Usage

Finding Files by Exact Name

One of the most common uses of find is locating files by their exact name. The -name option lets you specify the filename you’re searching for.

For example, to find a file named “document.txt” in your home directory:

find /home -name "document.txt"

This command will search through the entire /home directory and its subdirectories, displaying the full path to any file named exactly “document.txt”.

It’s important to note that the search is case-sensitive by default. If you’re unsure about the exact capitalization, you can use the -iname option for a case-insensitive search:

find /home -iname "document.txt"

Finding Files by Approximate Name

Often, you might remember only part of a filename or want to find files of a certain type. This is where wildcards become invaluable.

To find all text files in your home directory:

find ~ -name "*.txt"

The asterisk (*) acts as a wildcard, matching any number of characters. In this example, it will find all files ending with the .txt extension.

For more flexible searches, you can use wildcards in different positions:

find /home -iname "*doc*"

This command will find all files that have “doc” anywhere in their name, regardless of case.

When using wildcards, it’s important to enclose the pattern in quotes to prevent the shell from expanding them before the find command receives them. Without quotes, the shell might interpret the wildcards and change the behavior of your search unexpectedly.

Finding Files by Type

Linux categorizes files into different types, and find allows you to search specifically for certain file types using the -type option.

The most common file type indicators include:

  • f for regular files
  • d for directories
  • l for symbolic links (symlinks)
  • b for block devices
  • c for character devices
  • p for named pipes
  • s for sockets

To find all directories in the current path:

find . -type d

To locate all symbolic links in the /usr directory:

find /usr -type l

You can combine type searches with name patterns for more specific results:

find /etc -type f -name "*.conf"

This will find all regular files (not directories or links) with names ending in .conf within the /etc directory and its subdirectories.

Finding Files by Size

When disk space becomes a concern, finding files based on their size becomes crucial. The find command offers robust options for size-based searches using the -size parameter.

Size specifications in find use the following units:

  • c for bytes
  • k for kilobytes (1024 bytes)
  • M for megabytes (1024 kilobytes)
  • G for gigabytes (1024 megabytes)

To search for files larger than a specific size, use the + prefix:

find /var/log -size +100M

This command locates all files in /var/log and its subdirectories that are larger than 100 megabytes.

For files smaller than a certain size, use the - prefix:

find /home -size -10k

To find files of an exact size, omit both prefixes:

find /path -size 0

This will find all empty files (size exactly 0 bytes).

You can also combine size criteria for range-based searches:

find /home -size +5M -size -100M

This finds files between 5MB and 100MB in size, which can be particularly useful when hunting for specific types of files that typically fall within a certain size range.

Finding Files by Time Attributes

Linux maintains three distinct timestamps for each file:

  • Modification time (mtime): when the file’s content was last modified
  • Access time (atime): when the file was last read
  • Change time (ctime): when the file’s metadata (permissions, ownership) was last changed

The find command provides options to search based on all these time attributes.

To find files modified in the last 7 days:

find /path -mtime -7

To find files not accessed in the last 30 days:

find /path -atime +30

To find files whose metadata changed within the last day:

find /path -ctime -1

For more precise searches, find also offers minute-based options:

  • -mmin (modification time in minutes)
  • -amin (access time in minutes)
  • -cmin (change time in minutes)

For example, to find files modified in the last 60 minutes:

find /path -mmin -60

These time-based searches are particularly useful for maintenance tasks, such as identifying old log files or locating recently modified configuration files during troubleshooting.

Finding Files by Permissions and Ownership

File permissions and ownership are fundamental aspects of Linux security. The find command allows you to search for files based on these attributes.

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

find /path -perm 644

This locates files with permissions set exactly to 644 (read/write for owner, read-only for group and others).

For more flexible permission matching, you can use:

  • -perm -mode to find files where all specified bits are set
  • -perm /mode to find files where any of the specified bits are set

To find files owned by a specific user:

find /home -user username

Similarly, to find files owned by a specific group:

find /var -group www-data

These options are particularly useful for security audits or when transferring file ownership after system changes.

Logical Operators with Find

To create more complex search criteria, find supports logical operators:

  • -and or simply a space between expressions (default)
  • -or for alternative conditions
  • -not or ! for negation

For example, to find all log files larger than 10MB:

find /path -name "*.log" -and -size +10M

To find files that are either text or document files:

find /path -name "*.txt" -or -name "*.doc"

To find all files not owned by a specific user:

find /path -not -user john

For complex queries, you can use parentheses to group expressions. When using parentheses, remember to escape them to prevent shell interpretation:

find /path \( -name "*.jpg" -or -name "*.png" \) -and -size +1M

This finds all large image files that are either JPG or PNG format and larger than 1MB.

Executing Actions on Found Files

The find command’s true power emerges when combined with the ability to execute operations on found files using the -exec option.

The basic syntax for -exec is:

find [path] [criteria] -exec command {} \;

Where:

  • command is the command to execute
  • {} is replaced by the current file name
  • \; marks the end of the command

For example, to delete all temporary files:

find /path -name "*.tmp" -exec rm {} \;

To change permissions on all script files:

find /path -type f -name "*.sh" -exec chmod 755 {} \;

To search for text within found files:

find /path -name "*.conf" -exec grep "parameter" {} \;

For better performance when executing commands on multiple files, use the + terminator instead of \;:

find /path -name "*.log" -exec rm {} +

The difference is that -exec command {} \; runs the command once for each file, while -exec command {} + appends as many filenames as possible to the command, reducing the number of command executions.

Advanced Find Techniques

Controlling Search Depth

By default, find searches all subdirectories recursively without limits. To control how deep find descends into the directory tree, use the -mindepth and -maxdepth options:

find /path -mindepth 2 -maxdepth 4 -name "*.txt"

This searches for text files starting at the second level of subdirectories (skipping the start directory) and going no deeper than the fourth level.

These options help optimize searches by limiting the scope to relevant directory depths, which can significantly improve performance when working with deep directory structures.

Finding Empty Files and Directories

To locate empty files or directories, the -empty option is invaluable:

find /path -type f -empty

This finds all empty regular files.

find /path -type d -empty

This finds all empty directories, which is particularly useful for cleanup operations.

Excluding Directories from Search

Often, you may want to skip certain directories during a search, such as version control directories or cache folders. The -path and -prune options work together to achieve this:

find /path -path "*/cache" -prune -o -name "*.log" -print

This command searches for log files but skips any directory named “cache”. The -o is the “or” operator, and -print explicitly instructs find to print the results that match the right side of the “or” condition.

For multiple exclusions:

find /path -type f \( -path "*/node_modules/*" -o -path "*/vendor/*" \) -prune -o -name "*.js" -print

This finds JavaScript files while skipping the “node_modules” and “vendor” directories.

Optimizing Find Performance

The find command can be resource-intensive, especially when searching large filesystems. Here are some tips to improve performance:

  1. Limit the search scope: Always specify the most specific starting directory possible.
  2. Use appropriate depth controls: Apply -maxdepth when you know the files won’t be nested beyond a certain level.
  3. Search by filetype first: When combining criteria, place -type early in your expression to filter out irrelevant file types quickly.
  4. Consider alternatives: For simple filename searches, the locate command might be faster as it uses a pre-built database instead of searching the filesystem in real-time.
  5. Use xargs for efficiency: Instead of:
    find /path -type f -exec command {} \;

    Use:

    find /path -type f -print0 | xargs -0 command

    The -print0 and -0 options handle filenames with spaces safely.

Remember that find traverses filesystems sequentially, so searches on SSDs will typically be faster than on traditional hard drives.

Practical Find Command Examples

Here are some real-world examples of how find can solve common tasks:

Finding and removing old log files:

find /var/log -name "*.log" -type f -mtime +30 -exec rm {} \;

Finding files with specific content:

find /etc -type f -exec grep -l "password" {} \;

Finding large files for potential cleanup:

find /home -type f -size +100M -exec ls -lh {} \; | sort -k5,5hr

Finding duplicate files (by size and then MD5 hash):

find /path -type f -exec md5sum {} \; | sort | uniq -w32 -d

Finding files with special characters in their names:

find /path -name "*[[:space:]]*" -o -name "*[*]*"

These examples demonstrate the versatility of find for solving various file management and system administration challenges.

Find Command Cheat Sheet

Option Purpose Example
-name Find by exact filename find . -name "file.txt"
-iname Find by filename, case-insensitive find . -iname "file.txt"
-type Find by file type find . -type d (directories)
-size Find by file size find . -size +10M (>10MB)
-mtime Find by modification time (days) find . -mtime -7 (last 7 days)
-user Find by owner find . -user username
-perm Find by permissions find . -perm 644
-exec Execute command on matches find . -name "*.tmp" -exec rm {} \;
-maxdepth Limit directory traversal depth find . -maxdepth 2 -name "*.conf"
-empty Find empty files/directories find . -type f -empty

These quick references will help you construct effective find commands for various scenarios. Remember that proper quoting of search patterns prevents unexpected behavior and errors in your searches.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button