Searching for Files with find

Su Suriya Ravichandran Updated 06 Dec 2026
7 min read ·Lesson 20 of 205

When a project grows, files get lost in its directory tree. The find command walks through a directory tree and tests every item against conditions you describe, such as its name, type, size or age. It can then print the matches or run another command on each one. Unlike a graphical search, find reads the file system directly, so it works on any directory without an index and gives you precise control over what counts as a match.

Understanding the Concept

The general form of the command is:

find  START_DIRECTORY...  TESTS  ACTIONS

find starts at each start directory, visits every item below it, and evaluates your tests from left to right. When all tests are true for an item, the action runs. If you give no action, find prints the path, which is the same as writing -print.

The examples in this lesson use a small project. It was created with mkdir and touch, and docs/big.dat contains 2,048 bytes:

.
./.env
./.git/config
./README.md
./build/out.o
./docs/Notes.MD
./docs/big.dat
./docs/guide.md
./src/app.py
./src/main.py
./src/utils/helpers.py
./tests/test_app.py
./tests/test_main.py

All the commands below run from the top of this project, which is why the paths begin with ./. The command find . with no tests lists everything. find does not sort its output, so the examples pipe it through sort to make the order predictable.

Finding Files by Name

The test -name matches the file name against a pattern. The pattern must be quoted, so that find receives the asterisk instead of the shell expanding it:

find . -name "*.py" | sort

Output:

./src/app.py
./src/main.py
./src/utils/helpers.py
./tests/test_app.py
./tests/test_main.py

The match applies to the file name only, not to the directory part, and the pattern must match the whole name. -name is case sensitive, so readme.md does not match README.md:

find . -name "readme.md"
find . -iname "readme.md"

Output of the second command (the first prints nothing):

./README.md

The option -iname ignores case. It also lets one pattern catch both .md and .MD files:

find . -iname "*.md" | sort

Output:

./README.md
./docs/Notes.MD
./docs/guide.md

Why Quoting Matters

Suppose you run the search from inside src, where app.py and main.py exist, and you forget the quotes:

cd src
find .. -name *.py

Output:

find: paths must precede expression: `main.py'
find: possible unquoted pattern after predicate `-name'?

The shell expanded *.py into app.py main.py before find started, so find received two words after -name. The message tells you the cause. Quoting the pattern fixes it:

find .. -name "*.py" | sort

Output:

../src/app.py
../src/main.py
../src/utils/helpers.py
../tests/test_app.py
../tests/test_main.py

Finding Files by Type

The test -type selects the kind of item. The two most common values are f for regular files and d for directories:

find . -type d | sort

Output:

.
./.git
./build
./docs
./src
./src/utils
./tests

Combining tests means that all of them must be true, which acts as a logical AND:

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

Output:

./README.md
./docs/guide.md

Both files are regular files with names ending in .md. The ./docs/Notes.MD file is missing because -name is case sensitive.

Limiting the Depth

By default find descends through every level. The options -maxdepth and -mindepth restrict the levels it visits. The start directory itself is level 0.

find . -maxdepth 1 -type f | sort

Output:

./.env
./README.md

Only items directly inside the start directory are considered. To see only directories exactly two levels down:

find . -mindepth 2 -maxdepth 2 -type d

Output:

./src/utils

Put these options before other tests. GNU find prints a warning when a depth option comes after a test, because the order can matter.

Combining Conditions

Negation and Alternatives

Use ! or -not to invert a test, and -o for "or". Parentheses group tests, and since they have a meaning to the shell, they must be escaped with a backslash:

find . -type f -not -name "*.py" | sort

Output:

./.env
./.git/config
./README.md
./build/out.o
./docs/Notes.MD
./docs/big.dat
./docs/guide.md
find . \( -name "*.md" -o -name "*.MD" \) | sort

Output:

./README.md
./docs/Notes.MD
./docs/guide.md

Without the parentheses, a command such as find src docs -name "*.md" -o -name "*.py" still works for a plain print, but it breaks as soon as you add an action, because -o has lower priority than the implied AND. Grouping with 0 ... 1 avoids that.

Skipping Directories

Searching inside .git or build is usually a waste of time. The action -prune tells find not to descend into a directory:

find . -name .git -prune -o -type f -print | sort

Output:

./.env
./README.md
./build/out.o
./docs/Notes.MD
./docs/big.dat
./docs/guide.md
./src/app.py
./src/main.py
./src/utils/helpers.py
./tests/test_app.py
./tests/test_main.py

Read it as: "if the name is .git, prune it; otherwise, if it is a file, print it". The files inside .git do not appear. The shorter form ! -path "./.git/*" also works but still visits the directory.

Filtering by Size

The test -size accepts a number with a unit suffix. A plus sign means "larger than" and a minus sign means "smaller than":

find . -type f -size +1k

Output:

./docs/big.dat

Sizes are rounded up to whole units, so -size -1k means files that use zero units, in other words empty files. Use -empty to find empty files and directories explicitly:

find . -type d -empty

This prints nothing in the project, because no directory is empty. Suffixes include c (bytes), k (kibibytes), M (mebibytes) and G (gibibytes).

Filtering by Time

These tests work with timestamps:

TestMeaning
-mtime -NModified less than N days ago
-mtime +NModified more than N days ago
-mmin -NModified less than N minutes ago
-newer FILEModified more recently than FILE
-newermt "DATE"Modified after a given date

In the project, docs/guide.md was given an old date in January 2026. Searching for files modified more than 30 days ago finds it:

find . -type f -mtime +30

Output:

./docs/guide.md

To find files in a date range, combine -newermt with its negation:

find . -type f -newermt "2026-01-01" ! -newermt "2026-02-01"

Output:

./docs/guide.md

The file was modified after 1 January and not after 1 February. The results of time-based searches depend on when you run them, so expect different output from your own files.

Acting on the Results

Running a Command with -exec

The -exec action runs a command for each match. The braces {} stand for the file name, and the command ends with \; or +:

find . -name "*.md" -exec echo "file:" {} \; | sort

Output:

file: ./README.md
file: ./docs/guide.md

With \;, the command runs once for each file. With +, find passes as many file names as will fit to a single run, which is faster for large searches. This example lists the Python files that contain the word def, after src/main.py received a function:

echo "def f(): pass" > src/main.py
find . -name "*.py" -exec grep -l "def" {} +

Output:

./src/main.py

The grep -l option prints only the names of files with a match.

Deleting Files

The action -delete removes each match. It is powerful and should be used only after you have run the same command with -print to check the list:

find . -name "*.o" -print
find . -name "*.o" -print -delete

Output of the second command:

./build/out.o

Put -delete last. If it comes first, find deletes everything it visits before applying your tests.

Custom Output with -printf

The -printf action formats the output with codes such as %p for the path and %s for the size in bytes:

find . -type f -name "*.md" -printf "%p %s\n" | sort

Output:

./README.md 0
./docs/guide.md 0

Practical Applications

Handling Names With Spaces Safely

A pipeline that sends names to another command can break when a name contains a space or newline. The option -print0 ends each name with a null character, and xargs -0 reads it back correctly:

touch "src/my file.py"
find . -name "*.py" -print0 | xargs -0 -n1 echo | sort

Output:

./src/app.py
./src/main.py
./src/my file.py
./src/utils/helpers.py
./tests/test_app.py
./tests/test_main.py

The file my file.py stays intact as one name. A later lesson covers this technique in detail.

Counting Matching Files

Piping into wc -l counts the matches:

find . -type f | wc -l

The project now holds twelve regular files, so the command prints 12.

When the Start Directory Does Not Exist

find /nonexistent
echo "status=$?"

Output:

find: '/nonexistent': No such file or directory
status=1

Errors go to standard error, so when you search a large part of the system, you can hide them with 2>/dev/null.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Searching for Files with find and get answers drawn from it.

Signed-in readers only.