Locate files with the find tool

The find tool is another Linux gem that allows you to search for files based on a number of criteria including name, file size, modification date, etc. Using find will help you locate files that would otherwise take time to locate manually.

In its most basic form, find can print every file on the system:

$ find /


This would print out a list of every file. To search for a particular file name, use:

$ find / -name passwd

To search for files named passwd that have mode 0700 permissions:

$ find / -name passwd -perm 0700

If you wanted to find all files that were setuid root, you would use:

$ find /usr -perm 4755 -user root

If you wanted to clean all files from /tmp, but leave directories intact, you could use:

# find /tmp -type f -exec rm -f {} \;

This command looks for files of type f (regular file) and executes the command rm -f on each file (noted by {}). The command passed to -exec must be terminated with backslash, semicolon (\;). If, however, you wanted to find and delete only your files:

$ find /tmp -type f -user `whoami` -exec rm -f {} \;

This will only delete files belonging to the user executing the command.

If you want to search in the current directory and below, use a period (.) for the path. If you want to look for a file that was created after another file, use:

$ find . -cnewer somefile.txt

This will find and print out a list of all files created after somefile.txt.

Finally, if you want to search the current directory and below for any files changed in the last 30 days but that do not contain the string .svn and list the files:

$ find . -type f -ctime -30 -not -regex '.*svn.*' -exec ls {} -al \;

Here, a number of things are specified: any files that are of type f, that have a creation time of 30 days or less, but do not match the regular expression .*svn.* are then fed to ls as ls [file_match] -al. This also illustrates that the match characters ({}) do not have to be at the end of the command. Or, you could use the -print option instead of calling ls:

$ find . -type f -ctime -40 -not -regex '.*svn.*' -print

The find command is very powerful and there are a number of options and tests that can be performed to find certain types of files that match any number of specified criteria.

Delivered each Tuesday, TechRepublic's free Linux NetNote provides tips, articles, and other resources to help you hone your Linux skills. Automatically sign up today!