20+ find Command Examples in Linux

This tutorial explains Linux “find” command, options and its usage with examples.

The find command searches for files within a directory hierarchy. It evaluates the given expression from left to right, following precedence rules (see OPERATORS), until the outcome is determined (false for “and” operations, true for “or”). When an outcome is known, “find” proceeds to the next file name.

The first argument that begins with `-‘, `(‘, `)’, `,’, or `!’ is taken to be the beginning of the expression; any arguments before it are paths to search, and any arguments after it are the rest of the expression. If no paths are given, the current directory is used. If no expression is given, the expression `-print’ is used.

The find command exits with a status of 0 if all files are processed successfully and with a status greater than 0 if errors occur.

Syntax:

find [path...] [expression]

Options:

advertisement
advertisement
  • -daystart: Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago.
  • -depth: Process each directory’s contents before the directory itself.
  • -follow: Dereference symbolic links. Implies -noleaf.
  • -help, –help: Print a summary of the command-line usage of find and exit.
  • -maxdepth levels: Descend at most levels (a non-negative integer) levels of directories below the command line arguments. `-maxdepth 0′ means only apply the tests and actions to the command line arguments.
  • -mindepth levels: Do not apply any tests or actions at levels less than levels (a non-negative integer). `-mindepth 1′ means process all files except the command line arguments.
  • -mount: Don’t descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find.
  • -noleaf: This option turns off an optimization in the “find” command. By default, it assumes that directories have 2 fewer subdirectories than their hard link count. However, on filesystems like CD-ROM, MS-DOS, or AFS volumes, this may not hold true. Disabling this optimization prevents “find” from skipping file stats for faster searches.
  • -version, –version: Print the find version number and exit.
  • -xdev: Don’t descend directories on other filesystems.

Tests

Numeric arguments can be specified as:

  • +n: for greater than n.
  • -n: for less than n.
  • n: for exactly n.
  • -amin n: File was last accessed n minutes ago.
  • -anewer file: File was last accessed more recently than file was modified. -anewer is affected by -follow only if -follow comes before -anewer on the command line.
  • -atime n: File was last accessed n*24 hours ago.
  • -cmin n: File’s status was last changed n minutes ago.
  • -cnewer file: File’s status was last changed more recently than file was modified. -cnewer is affected by -follow only if -follow comes before -cnewer on the command line.
  • -ctime n: File’s status was last changed n*24 hours ago.
  • -empty: File is empty and is either a regular file or a directory.
  • -false: Always false.
  • -fstype type: Use this to specify the filesystem type for your search. Valid types vary (like ufs, nfs). You can use -printf with %F to see your filesystem types.
  • -gid n: File’s numeric group ID is n.
  • -group gname: File belongs to group gname (numeric group ID allowed).
  • -ilname pattern: Like -lname, but the match is case insensitive.
  • -iname pattern: Like -name, but the match is case insensitive. For example, the patterns `fo*’ and `F??’ match the file names `Foo’, `FOO’, `foo’, `fOo’, etc.
  • -inum n: File has inode number n.
  • -ipath pattern: Like -path, but the match is case insensitive.
  • -iregex pattern: Like -regex, but the match is case insensitive.
  • -links n: File has n links.
  • -lname pattern: File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/’ or `.’ specially.
  • -mmin n: File’s data was last modified n minutes ago.
  • -mtime n: File’s data was last modified n*24 hours ago.
  • -name pattern: Match file names (without directories) using a shell pattern. Ignore metacharacters at the start (e.g., * or ?). To exclude a directory and its files, use -prune.
  • -newer file: File was modified more recently than file. -newer is affected by -follow only if -follow comes before -newer on the command line.
  • -nouser: No user corresponds to file’s numeric user ID.
  • -nogroup: No group corresponds to file’s numeric group ID.
  • -path pattern: Match file names with a shell pattern. Metacharacters like / or . are treated as regular characters. To exclude a directory tree, use -prune. For example: find . -path ‘./src/emacs’ -prune -o -print.
  • -perm mode: File’s permission bits are exactly mode (octal or symbolic). Symbolic modes use mode 0 as a point of departure.
  • -perm -mode: All of the permission bits mode are set for the file.
  • -perm +mode: Any of the permission bits mode are set for the file.
  • -regex pattern: Match file names with regular expressions. It applies to the whole path. For example, to match a file named `./fubar3′, you can use the regular expression `.*bar.’ or `.*b.*3′, but not `b.*r3′.
  • -size n[bckw]: Match files of a specific size, with units like bytes (b), kilobytes (k), etc. Size excludes certain blocks, but includes those in sparse files.
  • -true: Always true.
  • -type c: File is of type c.
  • -type b: block (buffered) special
  • -type c: character (unbuffered) special
  • -type d: directory
  • -type p: named pipe (FIFO)
  • -type f: regular file
  • -type l: symbolic link
  • -type s: socket
  • -type D: door (Solaris)
  • -uid n: File’s numeric user ID is n.
  • -used n: File was last accessed n days after its status was last changed.
  • -user uname: File is owned by user uname (numeric user ID allowed).
  • -xtype c: The same as -type unless the file is a symbolic link.

Operators

Listed in order of decreasing precedence:

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
  • ( expr ): Force precedence.
  • ! expr: True if expr is false.
  • -not expr: Same as ! expr.
  • expr1 expr2: And (implied); expr2 is not evaluated if expr1 is false.
  • expr1 -a expr2: Same as expr1 expr2.
  • expr1 -and expr2: Same as expr1 expr2.
  • expr1 -o expr2: Or; expr2 is not evaluated if expr1 is true.
  • expr1 -or expr2: Same as expr1 -o expr2.
  • expr1 , expr2: List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2.

Expressions

The expression is made up of options (which affect overall operation rather than the processing of a specific file, and always return true), tests (which return a true or false value), and actions (which have side effects and return a true or false value), all separated by operators. -and is assumed where the operator is omitted. If the expression contains no actions other than -prune, -print is performed on all files for which the expression is true.

Actions

  • -exec command ; Execute a command; return true if it exits without errors. Following arguments are treated as arguments to the command until a `;’ is found. ‘{}’ is replaced with the current file name. These may need special handling to prevent issues with the shell. The command runs in the starting directory.
  • -fls file: True; like -ls but write to file like -fprint.
  • -fprint file: True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names “/dev/stdout” and “/dev/stderr” are handled specially; they refer to the standard output and standard error output, respectively.
  • -fprint0 file: True; like -print0 but write to file like -fprint.
  • -fprintf file format: True; like -printf but write to file like -fprint.
  • -ok command ; Like -exec but ask the user first (on the standard input); if the response does not start with `y’ or `Y’, do not run the command, and return false.
  • -print: True; print the full file name on the standard output, followed by a newline.
  • -print0: True; print the full file name on the standard output, followed by a null character. This allows file names that contain newlines to be correctly interpreted by programs that process the find output.
  • -printf format: True; print format on the standard output, interpreting `\’ escapes and `%’ directives. Field widths and precisions can be specified as with the `printf’ C function. Unlike -print, -printf does not add a newline at the end of the string.
  • -prune: If -depth is not given, true; do not descend the current directory.
    If -depth is given, false; no effect.
  • -ls: True; list current file in `ls -dils’ format on standard output. The block counts are of 1K blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used.

find Command Examples:

1. Find Files Under Home Directory

# find /home -name tecm.txt
 
/home/tec.txt

2. Find Files Using Name and Ignoring Case

advertisement
# find /home -iname tec.txt
 
./tec.txt
./Tec.txt

3. Find Directories Using Name

Find all directories whose name is Tec in / directory.

# find / -type d -name Tec
 
/Tec

4. Find all PHP Files in Directory

advertisement
# find . -type f -name "*.php"
 
./register.php
./login.php
./index.php

5. Find Files with 777 Permissions and Chmod to 644

# find / -type f -perm 0777 -print -exec chmod 644 {} \;

6. Find and remove single File

# find . -type f -name "tec.txt" -exec rm -f {} \;

7. Find and remove Multiple File

# find . -type f -name "*.txt" -exec rm -f {} \;

8. Find all Empty Files/Directories

Files:

# find /tmp -type f -empty

Directories:

# find /tmp -type d -empty

9. File all Hidden Files

# find /tmp -type f -name ".*"

10. Find all Files Based on User

# find /home -user abc1
 
/home/a.txt
/home/b.txt
/home/a.cpp

11. Find all Files Based on Group

To find all files that belongs to group Developer under /home directory.

# find /home -group developer

12. Find Particular Files of User

To find all .txt files of user abc1 under /home directory.

# find /home -user abc1 -iname "*.txt"
 
/home/a.txt
/home/b.txt

13. Find Last 50 Days Accessed Files

# find / -atime 50

14. Find Last 50-100 Days Modified Files

# find / -mtime +50 –mtime -100

15. Find Changed Files in Last 1 Hour

# find / -cmin -60

16. Find Size between 50MB – 100MB

# find / -size +50M -size -100M

17. Find and Delete 100MB Files

# find / -size +100M -exec rm -rf {} \;

18. Find Specific Files and Delete

Find all .mp3 files with more than 10MB and delete them using one single command.

# find / -type f -name *.mp3 -size +10M -exec rm {} \;

19. Limit Search To Specific Directory Level Using mindepth and maxdepth

Find the passwd file under all sub-directories starting from root directory.

# find / -name passwd
./usr/share/doc/nss_ldap-253/pam.d/passwd
./usr/bin/passwd
./etc/pam.d/passwd
./etc/passwd

Find the passwd file under root and one level down. (i.e root — level 1, and one sub-directory — level 2)

# find -maxdepth 2 -name passwd
./etc/passwd

Find the passwd file under root and two levels down. (i.e root — level 1, and two sub-directories — level 2 and 3 )

# find / -maxdepth 3 -name passwd
./usr/bin/passwd
./etc/pam.d/passwd
./etc/passwd

Find the password file between sub-directory level 2 and 4.

# find -mindepth 3 -maxdepth 5 -name passwd
./usr/bin/passwd
./etc/pam.d/passwd

20. Inverting the match.

Shows the files or directories whose name are not MyCProgram.c .Since the maxdepth is 1, this will look only under current directory.

# find -maxdepth 1 -not -iname "MyCProgram.c"
.
./MybashProgram.sh
./create_sample_files.sh
./backup
./Program.c

21. Find files which are modified after modification of a particular FILE

Following example displays all the files which are modified after the /etc/passwd files was modified. This is helpful, if you want to track all the activities you’ve done after adding a new user.

# find -newer /etc/passwd

22. Find files which are accessed after modification of a specific FILE

Following example displays all the files which are accessed after modifying /etc/hosts. If you remember adding an entry to the /etc/hosts and would like to see all the files that you’ve accessed since then, use the following command.

# find -anewer /etc/hosts

23. Executing two find commands at the same time

The following find command example, traverse the filesystem just once, listing setuid files and directories into /root/suid.txt and large files into /root/big.txt.

# find /    \( -perm -4000 -fprintf /root/suid.txt '%#m %u %p\n' \) , \
 \( -size +100M -fprintf /root/big.txt '%-10s %p\n' \)

Sanfoundry Global Education & Learning Series – 1000 Linux Tutorials.

If you wish to look at all Linux commands and their usage examples, go to Linux Commands Tutorial.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.