The find command allows you to recursively search and locate files on your system based on specific criteria. You can search by name, owner, group, type, permissions, date, as well as many others.
The find command uses the following format:
find [search_path(s)] [search_criteria]
The following is the most basic way to run the find command. It will list every file and directory within your current working directory.
$ find
This produces the same output but you are specifically listing the current directory as the search path.
$ find .
To search the entire filesystem, specify root as the search path (this could take a long time).
$ find /
You may want to redirect stderr to “/dev/null” to separate the valid output from the errors you might encounter from searching in directories where you don’t have the correct permissions.
$ find / 2> /dev/null
To search for a file with a specific name. This will find all files named “myfile” within your home directory.
$ find ~/ -name myfile
This will find all files with a “.jpg” extension in your home directory. The double quotes are needed so the shell will not expand the wildcards in the search string before it passes it to the find command.
$ find ~/ -name "*.jpg"
You can limit the depth level of the search as well. Set the value to 1 to search within the specified directory without recursing into any subdirectories. Raising the value will extend the search into that many directory levels.
$ find ~/ -name "*.jpg" -maxdepth 1
Search for files by permissions. This will find all files in your home directory that have rwx permissions for everyone.
$ find ~/ -perm 777
Search for executables.
$ find ~/ -executable
Search for files in your home directory which have been modified in the last twenty-four hours.
$ find ~/ -mtime 0
Search for files that are owned by the user “ryan”.
$ find / -user ryan
The find command is great for locating files but you can also execute commands on those files that it finds. To execute commands use the ‘-exec‘ option. The command below will perform an ‘ls -l‘ on each jpeg file it finds in your home directory.
$ find ~/ -name "*.jpg" -exec ls -l {} \;
The ‘-ok‘ option is similar to ‘-exec‘ but it will prompt you for confirmation before executing each command. This is helpful when you want to execute a potentially dangerous command such as removing files with rm like the example below.
$ find ~/ -name "*.jpg" -ok rm {} \;
< rm ... /home/ryan/pic1.jpg > ? n < rm ... /home/ryan/pic2.jpg > ? n < rm ... /home/ryan/pic3.jpg > ? n