Website Vidya
Linux & ServersStep-by-Step Guide

find Command in Linux: Search Syntax, Flags & Examples

Learn find command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
9 min read
PDF Cheat Sheet
find Command in Linux: Search Syntax, Flags & Examples
AI Executive SummaryWebsiteVidya AI

9 min read

Learn find command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What find Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

Interactive Builder for this Guide

Build your custom find syntax (find Command in Linux: Search Syntax, Flags & Examples)

Generated POSIX Command
find /var/log -maxdepth 4 -type f -name '*.log' -size +50M -mtime +14 -exec ls -lh {} +
Searches inside /var/log for matching entries matching *.log.
Flag-by-Flag Breakdown
/var/logStarting root directory to traverse
-maxdepth 4Descend at most 4 directory levels
-type fMatch only regular files
-name '*.log'Filter filename glob (case-sensitive)
-size +50MMatch files larger than 50M
-mtime +14Modified more than 14 days ago
-exec ls -lh {} +Batch matched paths cleanly into ls -lh

Server administration, security auditing, and automated storage maintenance rely heavily on the find command in linux. As a core member of the GNU findutils package, find provides the most comprehensive and flexible engine for searching filesystem hierarchies in real time.

Unlike database-driven lookup tools like locate that query pre-computed static indices, find traverses the physical directory tree live. It inspects filesystem inodes directly, enabling precise filtering by file type, byte size, modification timestamp, owner user and group, permission mode bits, and extended attributes.

Beyond merely listing file paths, find functions as a powerful pipeline orchestrator. Using action expressions like -exec, -delete, and -print0 paired with xargs -0, administrators can safely process batches of thousands of files—even those with spaces, quotes, and newlines in their names—without security vulnerabilities.

Advertisement
find Command in Linux: Search Syntax, Flags & Examples — syntax, flags, and practical terminal workflow diagram
find Command in Linux: Search Syntax, Flags & Examples — command syntax, key options, and production workflow reference.

What find Does and When to Use It

Under the hood, GNU find traverses directory trees using the POSIX openat(2), fdopendir(3), readdir(3), and fstatat(2) system calls. To optimize performance, modern find inspects the d_type field returned by readdir(3) when supported by the filesystem (ext4, XFS, Btrfs). This allows find to evaluate -type f or -type d filters directly without issuing an expensive fstatat(2) system call on every individual file, dramatically accelerating directory traversal.

Furthermore, find tracks directory hard link counts (st_nlink). On traditional Unix filesystems, a directory's link count equals 2 plus the number of subdirectories it contains (due to . and .. entries). GNU find uses this optimization to know when all subdirectories of a folder have been visited, stopping further searches in that folder early unless the -noleaf option is specified (required on filesystems that do not follow Unix link conventions, such as FAT and CD-ROMs).

At the operating system level, find (distributed in findutils) interfaces with the Linux kernel through standard C library system calls and virtual filesystems. Understanding how find resolves file descriptors, kernel structures, and exit status codes helps system administrators predict performance on high-load production servers.

Availability and Installation Across Linux Distributions

The find utility is packaged in findutils across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether find is installed and inspect which binary path and version your shell resolves:

type -a find
find --version 2>/dev/null || man -f find

# Illustrative output (reviewed against documentation)
find is /usr/bin/find
find (findutils)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y findutils

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y findutils

# Arch Linux
sudo pacman -S --noconfirm findutils

# Alpine Linux
sudo apk add --no-cache findutils

Command Syntax, Arguments, and Exit Status Codes

find [-H] [-L] [-P] [path...] [expression]

The syntax is find [path...] [expression]. If path is omitted, find defaults to the current working directory (.). The expression consists of operators, options, tests, and actions evaluated from left to right. Logical operators include -and (default between expressions), -or (or -o), and -not (or !).

Common tests include -name (case-sensitive glob), -iname (case-insensitive glob), -type (f for regular file, d for directory, l for symlink), -size (e.g. +100M), -mtime (modification time in days), and -perm (permission mode bits). Primary actions include -print (default), -print0 (null-delimited output), -delete, and -exec COMMAND {} +.

  • 0 — All specified directories were traversed and all tests/actions completed successfully.
  • 1 — Operational failure, such as encountering unreadable directories or permission errors during traversal.
  • 2 — Malformed expression syntax or invalid command-line option supplied.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-name <PATTERN>Name FilterMatches base filename against shell wildcard pattern (e.g. '*.log').
-iname <PATTERN>Case-InsensitiveMatches base filename ignoring case distinctions.
-type <X>File TypeFilters by file type: f (file), d (directory), l (symlink), s (socket), p (pipe).
-size <[+-]N[cwbkMG]>Size FilterMatches files greater (+) or smaller (-) than N units (k=KiB, M=MiB, G=GiB).
-mtime <[+-]N>Mod Time (Days)Matches files modified more than (+) or less than (-) N 24-hour periods ago.
-mmin <[+-]N>Mod Time (Minutes)Matches files modified more than (+) or less than (-) N minutes ago.
-perm <MODE>PermissionsMatches files by exact octal permissions, -MODE (all bits set), or /MODE (any bit set).
-exec CMD {} +Action ExecutorExecutes command on matching files in optimized batches; {} is replaced by filenames.

Understanding the difference between -exec CMD {} \; and -exec CMD {} + is one of the most critical performance optimizations in Linux. Using \; spawns a separate child process for every single matching file (e.g. 10,000 files = 10,000 process forks). Using + aggregates files into batches, passing hundreds of filenames per process invocation—identical to xargs but built directly into find.

Advertisement

When scripting deletion, prefer -delete or -print0 | xargs -0 rm over naive piping like find | xargs rm. File paths containing spaces, single quotes, double quotes, or newlines break standard whitespace-separated pipelines, while null-delimited (-print0 / -0) streams handle arbitrary characters safely.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Find Files by Name Case-Insensitively

Locate all markdown documents across a project regardless of uppercase or lowercase extension.

find . -type f -iname "*.md"

# Illustrative output (reviewed against documentation)
./README.md
./docs/architecture.md
./changelog.MD

-type f isolates regular files, and -iname matches both .md and .MD extensions.

2. Find Files Larger Than 100 Megabytes

Scan /var/log for large files consuming significant disk space.

find /var/log -type f -size +100M -exec ls -lh {} +

# Illustrative output (reviewed against documentation)
-rw-r----- 1 root adm 142M Oct 22 21:40 /var/log/syslog.1
-rw-r----- 1 root adm 210M Oct 22 21:41 /var/log/journal/system.journal

-size +100M matches files larger than 100 Megabytes, and -exec ls -lh displays formatted sizes.

3. Find and Delete Files Modified More Than 30 Days Ago

Clean old temporary files that have not been modified in the last month.

find /tmp/app_cache -type f -name "*.tmp" -mtime +30 -delete

-mtime +30 matches files older than 30 days, and -delete removes them atomically.

4. Locate Insecure World-Writable Files on the System

Audit the filesystem for security vulnerabilities by locating non-symlink world-writable files.

find /etc -type f -perm -0002 -exec ls -l {} +

-perm -0002 checks if the other-write bit is set; clean output indicates proper security hardening.

5. Find Empty Directories and Prune Them Safely

Identify and remove empty directory hierarchies without touching files.

find /var/cache -type d -empty -exec rmdir -v {} +

# Illustrative output (reviewed against documentation)
rmdir: removing directory, '/var/cache/empty_stage'

-type d -empty isolates folders with zero child entries, passing them to rmdir for safe removal.

6. Stream Paths with Null Delimiters to xargs (-print0)

Safely process files containing spaces and special characters with xargs -0.

find /srv/uploads -type f -name "*.jpg" -print0 | xargs -0 -r chmod 644

-print0 outputs filenames separated by ASCII NUL characters, ensuring xargs -0 parses paths flawlessly.

Real-World Workflows, Pipelines, and Shell Automation

Automated Production Log Retention and Archive Sweep

Implement a production maintenance script that compresses logs older than 7 days and permanently purges logs older than 90 days across application log directories.

LOG_ROOT="/var/log/custom-services"

if [ -d "$LOG_ROOT" ]; then
  echo "Compressing uncompressed logs older than 7 days..."
  find "$LOG_ROOT" -type f -name "*.log" -mtime +7 ! -name "*.gz" -exec gzip -9 {} +

  echo "Purging compressed logs older than 90 days..."
  find "$LOG_ROOT" -type f -name "*.log.gz" -mtime +90 -print -delete

  echo "Log maintenance completed successfully."
fi

# Illustrative output (reviewed against documentation)
Compressing uncompressed logs older than 7 days...
Purging compressed logs older than 90 days...
Log maintenance completed successfully.

This two-tier retention policy compresses medium-age logs to save disk space and automatically purges old archives.

File Integrity and Security Audit Workflow

Scan critical system binary directories for newly modified files, unexpected SUID binaries, or files with unmapped owners (orphaned files).

echo "=== Auditing SUID/SGID Binaries in /usr/bin ==="
find /usr/bin -type f \( -perm -4000 -o -perm -2000 \) -exec ls -l {} + | head -n 5

echo "=== Checking for Orphaned Files with No Valid Owner ==="
find /tmp /var/tmp -nouser -o -nogroup 2>/dev/null || true

echo "=== Checking for System Binaries Modified in Last 24 Hours ==="
find /usr/bin /usr/sbin -type f -mtime -1 2>/dev/null || echo "No recently modified system binaries."

# Illustrative output (reviewed against documentation)
=== Auditing SUID/SGID Binaries in /usr/bin ===
-rwsr-xr-x 1 root root 85064 Oct 22 20:00 /usr/bin/chfn
-rwsr-xr-x 1 root root 52880 Oct 22 20:00 /usr/bin/chsh
-rwsr-xr-x 1 root root 88304 Oct 22 20:00 /usr/bin/gpasswd
-rwxr-sr-x 1 root mail 22896 Oct 22 20:00 /usr/bin/mail-touchlock
-rwsr-xr-x 1 root root 63960 Oct 22 20:00 /usr/bin/passwd
=== Checking for Orphaned Files with No Valid Owner ===
=== Checking for System Binaries Modified in Last 24 Hours ===
No recently modified system binaries.

This multi-check security audit identifies potential rootkits, unauthorized binary modifications, and orphaned files.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding find inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

When running find on world-writable directories (like /tmp), never use -exec without quoting or pass output directly to unquoted shell loops. Attackers can create files with malicious names (e.g. containing semicolons, backticks, or newlines) to inject shell commands.

The -nouser and -nogroup tests are crucial for server security. When a user account is deleted from /etc/passwd, their files remain on disk with raw numeric UIDs. If a new user is created later with the same UID, they automatically inherit ownership of those orphaned files.

GNU/Linux, BSD, and BusyBox Implementation Differences

The find utility is specified by POSIX.1-2017, but many common flags are GNU extensions. Flags like -delete, -print0, -empty, -mmin, and -iname are supported across GNU findutils and BSD (macOS), but may be absent in strict POSIX or minimal BusyBox environments.

In strict POSIX environments, replace -print0 | xargs -0 with -exec CMD {} +, and replace -delete with -exec rm -f {} +.

Troubleshooting Common Errors and Diagnostics

find: paths must precede expression: -name

Root Cause: A wildcard argument like *.log was expanded by the shell into multiple filenames before find executed, causing find to misparse arguments.

Resolution: Always wrap search patterns in quotes: find . -name '*.log'.

find . -name "*.log"

find: 'path': Permission denied

Root Cause: The user lacks read or execute permissions on a directory in the search path.

Resolution: Run the command with sudo for system-wide searches, or redirect stderr with 2>/dev/null to silence permission errors.

find / -name "app.conf" 2>/dev/null

find: -delete: cannot remove directory: Directory not empty

Root Cause: The -delete flag processes directory subtrees in bottom-up order, but encounters files that failed prior filters, leaving the directory non-empty.

Resolution: Ensure you filter for files first (find . -type f -name '*.tmp' -delete), then prune empty directories separately.

find . -type f -name "*.tmp" -delete
find . -type d -empty -delete

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
Use the -iname option instead of -name: find /path -iname '*.png'. This matches file.png, file.PNG, and file.Png.
-mtime measures file modification time in 24-hour periods (days). -mmin measures modification time in exact minutes (e.g. -mmin -60 matches files modified within the past hour).
-exec command {} \; runs the command separately for each matching file, creating high process overhead. -exec command {} + aggregates matching files into batches, running the command on many files simultaneously for high performance.
Use the -prune action: find . -path './.git' -prune -o -name '*.js' -print. This instructs find to skip traversing the .git directory entirely.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout