The find
command in Linux enables powerful and versatile searches based on almost any file criteria imaginable. But with so much flexibility, it can seem intimidating for beginners. By walking through over 30 examples, this guide aims to help both new and experienced Linux users fully harness the capabilities of this invaluable tool.
A Brief History of Find
The find command has been part of UNIX and Linux since inception, with origins tracing back to venerable utilities like grep. As file systems evolved from simple to complex directory hierarchies, the need emerged to search and act on files meeting specific criteria.
Ken Thompson first implemented find as part of the UNIX Version 4 development in 1973. It quickly became an essential tool for tracking down misplaced files in increasingly large and complex UNIX environments. Early versions focused on searches bymodification time, but capabilities expanded swiftly.
Over 40 years later, find remains a staple in every Linux distribution. It can now leverage any file metadata attribute to conduct searches. The fundamentals have changed little thanks to UNIX traditionalism, ensuring continuity of knowledge. Mastering find is considered a rite of passage for any Linux shell user.
I rely on find daily to track down odd log entries, monitor suspicious file changes, batch edit permissions, and much more. I hope by the end of this guide you’ll fully appreciate find’s capabilities. So let’s get started!
When Should I Use the Linux Find Command?
The find tool scans directories recursively, seeking files that match your search criteria. This depth-first approach makes it suitable for:
- Locating misplaced files by name/type when you don’t know their path
- Cleaning directories by deleting/archiving old or big files
- Auditing permissions to address vulnerabilities
- Monitoring file changes that may indicate intrusions
- Complex batch editing like chown/chmod based on metadata
- Building advanced shell scripts that automatically maintain systems
Contrast this with simple file listings (ls) or fast database searches (locate) — find operates at a unique intersection of power, flexibility and speed. It fills a critical gap on essentially all Linux and UNIX-style distros.
If you need to search files by criteria like names, size, permissions, ownership, dates or conditions, find is likely the right tool for that job!
Now let’s dive into many examples demonstrating precisely how to leverage find for your needs.
Understanding Find Command Syntax and Options
The generic syntax of the Linux find command is as follows:
find [starting/root directory] [criteria/tests] [actions]
The most critical options and tests include:
Option | Description | Example |
---|---|---|
-name | Search by file name, supports wildcards | find /etc -name *.conf |
-iname | Case insensitive name search | find ~ -iname foo |
-size | Find files exceeding given size (+/-)#UNIT | find /var/log -size +10M |
-type | Filter by file type (d,f,l,b,c, etc) | find / -type d -name tmp |
-user | Search by file owner username | find /home -user john |
-group | Search by file group owner | find ~ -group admins |
-mtime | Files modified exactly n*24hrs ago | find / -mtime 10 |
-atime | Match files accessed exactly n*24hrs ago | find ~ -atime 7 |
-ctime | Match file metadata change time | find / -ctime -5 |
-perm | Find files with matching permissions | find /bin -perm 755 |
-exec | Execute commands/actions for each match | find . -name *.bak -exec rm {} \; |
Now let’s explore practical examples applying these parameters to meet various Linux file search needs.
1. How to Find a File by Name in Linux
The most basic usage of find is locating files by full or partial name, similar to grep or locate. For example:
# Locate file named access.log
find /var/log -name access.log
# Find files ending in .conf system-wide
sudo find / -name *.conf
# Search home folder for any .txt files
find ~ -name *.txt
Note find will return files matching the name pattern regardless of location. Using wildcards like * and ? provides extensive matching flexibility:
# Match configuration files with 1 letter between
find /etc -name ???.conf
# Find doc files ending in 1 or 2 digits
find ~ -name doc?.??
# Locate all files starting with temp
find /tmp -name "temp*"
By tweaking the search path and wildcards, you can locate files by name virtually anywhere on the filesystem.
2. Case Insensitive File Search with Find
By default, all Linux find searches are case sensitive, which can pose issues. The -iname
flag allows case insensitive matches, fixing this annoyance:
# Locate index.html or Index.htmL files
find . -iname "index.htm*"
# Find env files regardless of case
find /etc -iname "*.env"
# Case insensitive search for config.sys
find / -iname config.sys
I highly recommend making -iname
your default to avoid missed matches. Much more convenient!
3. How to Find Files by Type in Linux
The -type
option matches only specific file types denoted by one-letter codes, including:
Code | File Type |
---|---|
f | Regular file |
d | Directory |
l | Symbolic link |
For example, find only image files:
find ~ -type f -name "*.png"
Or just subdirectories called temp:
find / -type d -name temp
Executable scripts ending in .sh:
find /usr/bin -type f -name "*.sh"
And many more combinations work. This helps filter out unneeded directories/links from results.
Some bonus ones – b = block device, c = character device, p = pipe, s = socket. Leverage -type
when the file type matters.
4. Finding Files by Size Using Find
The -size
flag matches files equal or over a specified byte size. Append a unit like k/M/G or use bytes.
Locate files over 2 megabytes in size:
find ~ -size +2M
Find log files exceeding 100 kilobytes:
find /var/log -size +100k
List files with 3 gigabyte size exactly:
find /backup -size 3G
Anything smaller than 5 kilobytes:
find ~ -size -5k
This makes pruning huge files or temp data a breeze!
5. How to Find Files by Owner/User
Matching file owner usernames with -user
parameter enables permissions auditing.
Verify which files belong to user John:
sudo find /home -user john
Detect world-writable root files:
sudo find / -user root -perm -2
Ensure your own user files have correct ownership:
find ~ ! -user $(whoami)
And similar for advanced permission checks.
6. Search Files by Group Owner in Linux
Like user ownership, -group
seeks files belonging to the given POSIX group:
What files does "admin" group own?
find /etc -group admin
List NGINX files not owned by www group:
find /var/www -not -group www
Find dev group files with group write:
find /usr/local -group dev -perm -g+w
Handy for checking expected group permissions are in place.
7. Find Files by Permissions and Modes
The -perm
flag detects files with ANY matching permission bits from absolute, symbolic or octal modes. Consider:
Seeking world executable gives:
find /bin -perm -o=x
-o=x tests for execute (x) permission bit for world (o).
Matching exact octal 775 permission:
find ~ -perm 775
Identify any setuid/setgid files:
find / -perm -4000 -o -perm -2000
This shows the permission power of find for security use cases.
8. How to Find Files Modified Within Specified Days
The -mtime
option matches files changed exactly n*24hrs ago. For example:
See files modified less than 7 days ago:
find ~ -mtime -7
-7 = < 7 days.
List files not edited for over 180 days:
find ~/docs -mtime +180
Show tmp files from exactly 1 day ago:
find /tmp -mtime 1
Runs at midnight check last 24hr period.
9. Search for Files Accessed in Last n Days
Similar to mtime, -atime
seeks files read by user/process based on access time:
HTML files accessed within past 3 days:
find ~ -atime -3 -name *.html
Detect unused files older than 90 days:
find /var/tmp -atime +90
Report whoknows.txt accessed exactly 5 days ago:
find ~ -atime 5 -name "whoknows.txt"
Helps narrow down recently used files quickly.
10. How to Find Files Changed Within Last n Days
The -ctime
option matches file metadata/permission changes in last n days:
Detect suspicious hidden RC files edited last 48hrs:
sudo find / -ctime -2 -name ".*rc"
-2 means within 2 days
List /usr/bin files changed in last month:
sudo find /usr/bin -ctime -30
Great for attack forensics!
11. Combine File Find Filters for Precision
A key power of find is joining tests with AND (-a) / OR (-o) for precise results:
Big config files not owned by admins:
find /etc -size +1M ! -group admin
All executables with relative paths:
find ~ -perm 755 ! -path "/*"
Hidden dirs edited last 10+ days:
find / -name ".*" -a -ctime +10 -a -type d
By mixing match criteria you extract EXACTLY the results required. This filter ability is extremely valuable in productions environments to pinpoint issues.
12. Take Action On Files Matched by Find
So far we have only searched and printed results, but the -exec
flag runs commands and actions on matches.
Safely remove old application temp files:
find /tmp -name app*.tmp -atime +10 -exec rm {} \;
Locate and archive last 30 days web logs:
find /var/log/httpd -mtime -30 -name access.log -exec tar rf /tmp/weblogs.tar {} \;
Other common actions include move, copy, link, change permissions/ownership (chmod, chown) and more. This elevates find beyond searches into performing jobs as a batch processing tool.
13. Optimizing Find Speed for Faster File Searches
File system traversal carries overhead, so optimize find by:
-
Avoiding non-essential areas – Explicitly exclude dirs like /dev, /proc, /sys
-
Parallelizing searches – Multi-threading with GNU Parallel
-
Pre-caching metadata – updatedb and locate utilities
For example:
# Exclude special filesystems for speed
find / -mount ! -path /proc -a ! -path /sys -name *.log
# Spawn 8 parallel finds
find /etc -name *.conf | parallel -j8 grep foo {} \;
# Fallback to fast locate database
if ! find /var -name foo; then locate foo; fi
On large storage deployments, optimization is key!
14. Safely Handling Spaces and Special Characters
To avoid headaches, always:
- Quote search paths with spaces/parentheses/etc.
- Escape special characters like ?+[]/^\$.
- Use {} to pass files to commands
For example:
# Quote directory with parenthesis
find "(/var/old docs)" -type f
# Escape special characters match
find . -name "my+weird file[ext]"
# Pass safe filename to rm
find . -name "*.bak" -exec rm {} \;
Follow these habits with find to prevent undesirable expansion or globbing!
15. Additional Find Usage Tips
Here some miscellaneous but helpful Linux find usages:
- Match on octal file permissions like 755 or 644
- Search by inode number using -inum if you have it
- Exclude directories via ! -type d or files with ! -type f
- Use -empty and -depth options for advanced needs
- Sort results by last modified (-printf "%T@ %p\n")
- Leverage depth control for efficiency on huge disks
- Understand symlinks are dereferenced/followed by default
Find has dozens more options – review the man page for obscure details.
16. Chaining Find With Xargs for Batch Processing
The xargs command builds argument lists for other programs by reading stdin. Combined with find, it facilitates powerful multi-step batch jobs.
For example, collecting file access stats:
# Stat each file matched by find
find . -name *.md -print0 | xargs -0 stat –c ‘%A %a %n‘
And deleting oldest CSV files exceeding 1 GB:
# Delete large old csv files safely
find ~ -name *.csv -size +1G -printf "%T@ %p\n" | sort | head -10 | cut -d" " -f2- | xargs -d "\n" rm
This pipelines match → sort → head → cut → delete in one line!
The find + xargs combo enables easily scripting complex file workflows.
17. Crafting Efficient File Search Functions
You can encapsulate common find operations in shell functions for reuse:
# Find files by partial name
function ffind() {
find . -iname "*$1*"
}
# Delete files over 30 days old
function fclean() {
find . -atime +30 -delete
}
# Fetch stats on top 20 largest files
function fbiggest() {
find . -printf "%s\t%p\n" | sort -n | tail -20
}
Call as needed:
# User function instead
ffind tax doc
fclean
This technique helps tame intricate find use cases.
Final Thoughts on Mastering Linux Find
I hope walking through 30+ examples demystified the find command and revealed tricks for mastering usage. Some key takeaways include:
- Combine tests like -name, -size, -perm to extract the exact results needed
- Optimize search scope paths to avoid slow special filesystems
- Take action via -exec for batch file processing
- Encapsulate common queries in custom shell functions for reuse
- Learn advanced tips like exclusion, escaping spaces, xargs pipelines
Find enables unparalleled searches based on file metadata – this power will serve you for decades on whatever UNIX-like system you use!
Let me know in the comments if you have additional favorite find examples I may have missed. Thanks for reading!