File Searching and Finding (find, locate, which)
Category: Linux Command Basics
Type: Linux Commands
Generated on: 2025-07-10 03:05:39
For: System Administration, Development & Technical Interviews
File Searching and Finding (find, locate, which) - Linux Cheatsheet
Section titled “File Searching and Finding (find, locate, which) - Linux Cheatsheet”This cheatsheet provides a comprehensive guide to using find, locate, and which commands for locating files and directories in Linux. It’s designed for both beginners and experienced sysadmins and developers.
1. Command Overview
-
find: Recursively searches the directory tree for files matching specific criteria (name, size, modification time, etc.). Extremely powerful and flexible, but can be slow on large file systems. Best for precise searches with complex criteria. -
locate: Uses a pre-built database (usually updated daily) to quickly find files by name. Much faster thanfind, but may not be up-to-date if files have been recently created or moved. Best for quick searches by filename when accuracy isn’t critical. -
which: Locates the executable files associated with commands. Useful for determining which version of a command is being used (e.g., if multiple versions are installed). Best for finding the full path of a command.
2. Basic Syntax
-
find [path] [expression]path: The directory to start the search (defaults to current directory if omitted).expression: The criteria used to match files.
-
locate [options] patternpattern: The filename or pattern to search for.
-
which [options] commandcommand: The name of the command to find.
3. Practical Examples
find Examples:
-
Find all files named
myfile.txtin the current directory and its subdirectories:Terminal window find . -name myfile.txtOutput (example):
./path/to/myfile.txt./another/path/myfile.txt -
Find all files ending with
.login the/var/logdirectory:Terminal window find /var/log -name "*.log"Output (example):
/var/log/syslog/var/log/auth.log/var/log/kern.log -
Find all directories named
testdirunder/home:Terminal window find /home -type d -name testdirOutput (example):
/home/user1/testdir/home/user2/testdir -
Find all files larger than 10MB (10485760 bytes) in
/tmp:Terminal window find /tmp -size +10MOutput (example):
/tmp/large_file.dat/tmp/another_large_file.iso
locate Examples:
-
Find all files containing “report” in their name:
Terminal window locate reportOutput (example):
/home/user/documents/monthly_report.pdf/var/log/apache2/access_report.log -
Find all files containing “config” in their name, ignoring case:
Terminal window locate -i configOutput (example):
/etc/nginx/nginx.conf/home/user/.config/nvim/init.vim
which Examples:
-
Find the full path to the
python3command:Terminal window which python3Output (example):
/usr/bin/python3 -
Find all locations of the
javacommand:Terminal window which -a javaOutput (example):
/usr/bin/java/usr/lib/jvm/java-11-openjdk-amd64/bin/java
4. Common Options
find Options:
-name <pattern>: Find files matching the given filename pattern (supports wildcards).-iname <pattern>: Case-insensitive version of-name.-type <type>: Find files of a specific type (e.g.,ffor file,dfor directory,lfor symbolic link).-size <+|-size>: Find files of a specific size.+for greater than,-for less than, no sign for exactly. Size can be specified inc(bytes),k(kilobytes),M(megabytes),G(gigabytes).-mtime <+|-n>: Find files modifiedndays ago.+for older thanndays,-for newer thanndays.-atime <+|-n>: Find files accessedndays ago.-mmin <+|-n>: Find files modifiednminutes ago.-exec <command> {} \;: Execute a command on each found file.{}is replaced with the filename. The\;terminates the command. Warning: Use with caution, especially with destructive commands.-ok <command> {} \;: Like-exec, but prompts for confirmation before executing the command. Safer than-exec.-delete: Delete files that match the search criteria. Warning: Extremely dangerous. Double-check your criteria before using this.-print0: Prints filenames separated by null characters, useful for piping to other commands that can handle null-separated input (e.g.,xargs -0).-path <pattern>: Matches the entire file path, not just the filename.-regex <pattern>: Matches the entire file path using a regular expression.
locate Options:
-i: Case-insensitive search.-n <limit>: Limit the number of results.-c: Count the number of matching files.-r <regex>: Use a regular expression for the search pattern.-b: Match only the base name of the file (the filename without the directory path).-d <database>: Specify an alternate database to use.
which Options:
-a: Print all matching executable files, not just the first one.-v: Verbose output.--skip-alias: ignore aliases--skip-functions: ignore shell functions--skip-userspace: ignore userspace executables--all: Print all matching executable files, including aliases and functions. (same as -a)
5. Advanced Usage
find Advanced Examples:
-
Find files modified in the last 24 hours and execute
chmod 644on them:Terminal window find . -mtime -1 -type f -exec chmod 644 {} \;Safety Warning: This command will change permissions on all files found. Use
-okinstead of-execfor confirmation:Terminal window find . -mtime -1 -type f -ok chmod 644 {} \; -
Find all empty directories and delete them:
Terminal window find . -type d -empty -deleteSafety Warning: This command will permanently delete empty directories. Test it thoroughly before running it on a production system. Consider using
-printfirst to see which directories will be deleted. -
Find all files in
/var/www/htmlthat are owned by thewww-datauser and group and are world-readable, then remove world readability:Terminal window find /var/www/html -user www-data -group www-data -perm -002 -exec chmod o-r {} \; -
Find files modified in the last hour and pipe them to
xargsto compress them withgzip:Terminal window find . -mmin -60 -type f -print0 | xargs -0 gzip
locate Advanced Examples:
-
Find all files ending with
.confin/etc, using a regular expression:Terminal window locate -r "^/etc/.*\.conf$"Explanation:
^: Matches the beginning of the string./etc/: Matches the/etc/directory..*: Matches any character (.) zero or more times (*).\.conf: Matches.confliterally (escaped dot).$: Matches the end of the string.
6. Tips & Tricks
-
Updating the
locatedatabase: Thelocatecommand relies on a database. Update it regularly (usually done automatically by a cron job). To manually update the database, run:Terminal window sudo updatedb -
Combining
findwith other commands: Usefind -exec,find -ok, or piping withxargsto perform actions on the found files. -
Using
-print0withxargs -0: This is a safe way to handle filenames with spaces or special characters. -
Optimizing
findperformance: Avoid unnecessary recursion. Use more specific criteria to narrow down the search. Consider usinglocateif you only need to search by filename. -
Using
-quitwithfind: If you only need to find one matching file, you can use-quitto stop the search after the first match. This can significantly improve performance, especially on large filesystems. Example:find . -name "myfile.txt" -print -quit
7. Troubleshooting
locatenot finding recently created files: Thelocatedatabase needs to be updated. Runsudo updatedb.findtaking too long: Refine your search criteria. Start the search in a more specific directory.- Permission denied errors with
find: You may not have permission to access some directories. Try running the command withsudoor specify a different starting directory. - Issues with
-exec: Make sure the command you’re executing is valid and that the{}placeholder is correctly placed. Test the command on a single file first. Use-okfor safety. - **
find: missing argument to \-exec`:** Ensure you properly terminate the-execcommand with;`.
8. Related Commands
grep: Searches within files for lines matching a pattern.ls: Lists directory contents.stat: Displays file or file system status.file: Determines file type.du: Estimates file space usage.tree: Displays directory structure in a tree-like format.fd: A simpler and faster alternative tofind, written in Rust. (Requires installation).ripgrep(rg): Very fast recursive search tool. (Requires installation)
This cheatsheet provides a foundation for using find, locate, and which. Experiment with different options and combinations to become proficient in locating files and directories in Linux. Remember to exercise caution when using commands that can modify or delete files.