find walks a directory tree and prints every path that matches an expression: name, type, size, modification time, owner or permission. This cheat sheet covers those filters, finding files by one or many extensions, -exec and NUL-safe -print0 pipelines, plus excluding directories with -prune, empty directories, safe deletes, -regex, tar and rsync pipelines, find vs locate, finding where a command is installed (command -v vs which), and the macOS BSD differences.
The expression language is its own micro-DSL with order-sensitive operators and a handful of BSD versus GNU divergences that catch out scripts shipped between platforms. This page is the reference I keep open while writing batch-rename, cleanup, backup and pre-deploy scripts.
What does the find command do?
Every find command has the same three parts: where to start, which tests a path must pass, and what to do with the paths that pass.
# start tests action
find ./logs -type f -name '*.log' -mtime +30 -print./logs is the starting point (several are allowed, and . is the usual one). -type f -name '*.log' -mtime +30 are tests, joined by an implicit AND and evaluated left to right, so a directory is rejected at -type f before the name is checked. -print is the action, and it is the default when you give none. Swap it for -delete, -exec ... {} + or -print0 | xargs -0 and the same filter now acts on the files instead of listing them, which is why I always run a command with -print first. On Windows, PowerShell's Get-ChildItem -Recurse covers the same ground with different syntax.
Time and size reference
Keep these two tables in view while you set the inputs below. find measures time in days (-mtime) or minutes (-mmin), and size with a one-letter unit suffix.
Time filters:
| Want | Expression | Notes |
|---|---|---|
| Last N minutes | -mmin -N | Minute resolution |
| Last hour | -mmin -60 | |
| Last 24 hours | -mtime -1 | Same as -mtime 0 |
| Last N days | -mtime -N | - means "less than N ago" |
| Older than N days | -mtime +N | + means "more than N ago" |
| Exactly N days old | -mtime N | The 24-hour slice N days back (rarely what you want) |
| Newer than a file | -newer FILE | Exact-timestamp comparison |
Size units (-size suffix):
| Suffix | Unit | Example | Bytes |
|---|---|---|---|
c | bytes | -size +500c | 500 |
k | kibibytes | -size +10k | 10,240 |
M | mebibytes | -size +100M | 104,857,600 |
G | gibibytes | -size +1G | 1,073,741,824 |
+ before the value means "larger than", - means "smaller than", no sign means "exactly" (rounded up to the next whole unit).
Set your OS, search path, name pattern, time window, and size threshold. Every command below rewrites itself with your values. The time dropdown shows the find expression each option maps to.
Find by task (jump table)
Skim by intent and jump straight to the section. Every command updates with the values you set above.
| I want to... | Section |
|---|---|
| Find files by name (case-sensitive or not) | Find files by name |
| Match files with a regular expression | Match files with a regular expression |
| Find files by extension (one or many) | Find files by extension |
| Find only files, only directories, or only symlinks | Find files by type |
| Find (and delete) empty directories or empty files | Find empty directories |
| Find files larger or smaller than a threshold | Find files by size |
| Find the largest files on disk | Find largest files on disk |
| Find files modified in the last N days | Find files modified in the last N days |
| Find stale files not modified in N days | Find files not modified since |
| Find files owned by a user or with specific permissions | Find files by owner or permission + deep dive |
| Exclude a directory from the search | Exclude a directory from find |
| Run a command on every matched file | Run a command on every match |
| Run find operations in parallel, or choose -exec vs xargs | find with xargs -P |
| Safely pipe find output into another command | Pipe find safely into another command |
| Find files containing a specific string of text | Search file contents recursively |
| Delete files matched by find safely | Find and delete files |
| Archive matched files into a tarball | Archive find results with tar |
| rsync only the files find selected | rsync only the files find selected |
| Handle the macOS BSD vs GNU find differences | macOS BSD vs GNU find |
| Decide between find and locate | find vs locate vs mlocate |
| Find where a command (not a file) lives | Find where a command is installed |
| Avoid the common find footguns | Common find gotchas |
Find files by name
Match every file whose name matches a pattern. This is what 80% of find invocations do.
find :search_path -name ':pattern'Case-insensitive match (matches .log, .LOG, .Log all the same):
find :search_path -iname ':pattern'PowerShell's -Filter is case-insensitive by default, matching Windows' filesystem behavior. On Linux/macOS, -name is case-sensitive (-iname is the insensitive variant).
Limit how deep find recurses (avoid running away into a huge tree):
find :search_path -maxdepth 2 -name ':pattern'-maxdepth N is a GNU extension that BSD find also supports, despite being non-POSIX. Both macOS and Linux accept it.
-name takes a shell glob, not a regular expression: * is any run of characters, ? is exactly one character, [abc] is one character from a set, [a-z] one from a range, [!abc] one character not in the set. The glob is matched against the basename only, so find . -name 'src/*.ts' never matches (a basename never contains a slash). Always quote the pattern so the shell does not expand it before find sees it.
Find files by extension
find . -type f -name '*.txt' lists every .txt file under the current directory, at any depth. The *.txt is a glob, -type f keeps directories named something.txt out of the results, and the recursion is built in:
find :search_path -type f -name '*.txt'Several extensions: the OR group needs parens
To match several extensions, join -name tests with -o (OR) and wrap the whole group in escaped parentheses:
find . -type f \( -name '*.jpg' -o -name '*.png' -o -name '*.gif' \)The parens are not decoration. find joins adjacent tests with an implicit AND, and AND binds tighter than -o. Without the parens,
find . -type f -name '*.jpg' -o -name '*.png'parses as ( -type f AND -name '*.jpg' ) OR ( -name '*.png' ). The -type f only guards the first branch, so directories named *.png slip into the results, and an action like -delete appended to the end also binds to only part of the expression. The \( \) are escaped because bare parentheses are shell metacharacters; single-quoting them, '(' ... ')', works too. Rule of thumb: any time you use -o, wrap the OR group in \( \) and keep shared tests like -type f outside it.
Other tests stack outside the group the same way: find . -type f \( -name '*.jpg' -o -name '*.png' \) -size +500k reads as file AND (jpg OR png) AND larger than 500k.
Uppercase extensions and files with no extension
-name is case-sensitive, so IMG_1234.JPG does not match -name '*.jpg'. Camera files and files copied off Windows often carry uppercase extensions, which makes -iname the safer default for any media audit. Use it for every clause in the group; mixing -name and -iname in one OR group makes the result set look arbitrary:
find . -type f \( -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.png' \)The inverse query, every file whose name has no dot, is -not -name '*.*'. It finds extensionless scripts, Makefile, Dockerfile, README and suffix-free binaries:
find :search_path -type f -not -name '*.*'One subtlety: a dotfile like .gitignore has a leading dot and does match *.*, so it counts as having an extension here.
When the extension list gets long, a single -iregex alternation is shorter than a chain of -o clauses; the regular expression section below shows the jpg/jpeg/png case on both GNU and macOS. For two or three extensions in a script that must run on both platforms, I stay on the -name OR group, because -name and -iname behave identically on GNU and BSD find.
When find is not the right tool for extensions
- Inside a Git repository, when you only care about tracked files.
git ls-files '*.js'is faster and skipsnode_modules, build output and anything in.gitignore. - When you care about the real content type, not the suffix. A file called
data.txtcan hold a JPEG. Pipe matches throughfile(find . -type f -exec file {} +) and filter on its output. - One extension in one flat directory. A plain glob,
ls *.txtorfor f in *.txt, is simpler when there is no recursion and no extra filter.
Match files with a regular expression
-regex takes a full regular expression and matches it against the entire path, not the basename. That is the number one surprise: find . -regex '.txt' matches nothing, because find is testing paths like ./notes/todo.txt and the pattern only describes a three-character string. The leading .* soaks up the directories:
# -name is GLOB + basename: this is how you match *.txt files
find . -name '*.txt'
# -regex is REGEX + WHOLE PATH: the .* soaks up the leading ./dirs
find . -regex '.*\.txt'
# WRONG: regex syntax inside -name is read as a literal glob, matches nothing useful
find . -name '.*\.txt'The \. is an escaped, literal dot; a bare . in a regex means "any character", so .*.txt would also match mytxt. And a bare -regex '*.txt' is a malformed regex: in a regex, * means "zero or more of the previous token", and nothing precedes it. -iregex is the case-insensitive variant, exactly as -iname is to -name.
Pick the regex flavor with -regextype (GNU only)
GNU find lets you choose the flavor with -regextype, which must appear before the -regex test it governs (find reads the command line left to right):
-regextype value | Flavor | Notes |
|---|---|---|
emacs | Emacs regex | The GNU find default if you never pass -regextype |
posix-basic | POSIX BRE | ( and + are literals; groups need \( \) |
posix-extended | POSIX ERE | ( groups, + and ? work unescaped; what most people want |
posix-awk | awk regex | ERE-like, with awk's escape rules |
posix-egrep | egrep regex | ERE-like, matches old egrep behavior |
I pass -regextype posix-extended almost every time I use -regex on Linux. Here is the case that pushes me from -name to -regex: three image extensions. With -name it is three clauses joined by -o, grouped in escaped parentheses so the OR does not swallow later tests:
find :search_path -type f \( -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.png' \)With -regex it is one alternation, and jpe?g collapses jpg and jpeg into one token:
find :search_path -type f -regextype posix-extended -iregex '.*\.(jpe?g|png)'PowerShell's -match runs a .NET regex and, unlike find -regex, matches a substring by default, which is why the pattern is anchored with $.
-regex on macOS
BSD find has no -regextype flag at all: passing it is a hard error, not a warning. Its default flavor is basic POSIX, while GNU defaults to Emacs regex. So a Linux script using -regextype posix-extended -regex '.*\.(jpg|png)' fails outright on a Mac, and stripping the flag leaves an alternation that BSD's basic flavor may read as literal parentheses (\(jpg\|png\) is the BRE spelling). The macOS fix is the -E option, which goes before the path and switches -regex and -iregex to extended regex; that is why the macOS variant above reads find -E :search_path .... Without -E, macOS find reads (, | and ? in that pattern as BRE text and the command matches nothing. Since the flag goes in a different place on each platform (-E before the path on macOS, -regextype after it on Linux), I use the -name ... -o form in any script that must run on both, or install GNU findutils and call gfind.
Use -name for single extensions, prefixes, basename-only matches and anything cross-platform. Reach for -regex when the logic genuinely needs alternation across several patterns, a character class like [0-9], or anchoring against directory structure.
Find files by type
| Test | Matches |
|---|---|
-type f | Regular files |
-type d | Directories |
-type l | Symbolic links |
-type s | Sockets |
-type p | Named pipes (FIFOs) |
-type b | Block devices |
-type c | Character devices |
find :search_path -type f -name ':pattern'-type d combined with -empty is the classic cleanup query; it has its own section next.
Find empty directories
find . -type d -empty lists every empty directory under the path; swap in -type f for every empty (zero-byte) file. Drop the -type filter and find . -empty returns both, which is fine for an inventory but rarely what you want before a delete.
find :search_path -type d -empty
find :search_path -type f -emptyWhat "empty" means
A file is empty at zero bytes; a single newline is content. A directory is empty only with zero entries, and that is where the surprises live:
- A directory holding one subdirectory is not empty, even if that subdirectory is itself empty.
- A directory holding one hidden file (
.gitkeep,.DS_Store,.env) is not empty.-emptydoes not skip dotfiles. - A directory holding a broken symlink is not empty; the link is still an entry.
The hidden-file case is the most common reason find -type d -empty returns fewer directories than expected. A folder that looks blank in Finder can hold a .DS_Store. Run ls -la (note the -a) before assuming find is wrong.
Delete empty directories with -depth
find :search_path -depth -type d -empty -deleteBy default find processes a directory before its contents. Picture a/b/c where only c is empty: without -depth, find visits a (holds b, skip), then b (holds c, skip), then deletes c. Only the innermost leaf goes. With -depth, find visits c first and deletes it, then b is empty in time to be deleted, then a. The whole nested tree collapses in one pass.
-delete implies -depth in modern GNU and BSD find, so the bare form often works. I still write -depth explicitly, right after the search path, so the intent is obvious and the command stays correct if -delete is later swapped for -exec rmdir.
The two-pass cleanup
A directory full of empty files has entries, so a single directory pass will not touch it. Delete the empty files first, then the directories that pass just emptied:
find :search_path -type f -empty -delete
find :search_path -depth -type d -empty -deleteRun them in the other order and the directory pass skips folders the file pass would have emptied. This is the pattern I reach for after a failed export, a half-finished rsync, or a build that scattered placeholder files. Exclude subtrees with -not -path '*/node_modules/*' (or -prune, see Exclude a directory from find), and count instead of list with | wc -l. -empty, -depth, -delete, -not, -path and -prune all behave the same on BSD and GNU find. Do not run any of this against /: it walks /proc, /sys and every mount, and deletes empty directories the OS may depend on. Empty directories take essentially no disk space, so if the goal is freeing gigabytes, look at the largest files on disk instead.
Find files by size
Set the Size value and Size unit in the panel above (the unit table is in Time and size reference). + means larger than, - means smaller than.
find :search_path -type f -size +:{size_value}:{size_unit}For "smaller than", flip the + to -: find :search_path -type f -size -:{size_value}:{size_unit}.
Find the biggest log files on disk, sorted largest first:
find :search_path -type f -name ':pattern' -printf '%s %p\n' | sort -rn | head -20-printf is GNU only. On BSD use -exec stat with the BSD stat format flags. That difference is one of the most common scripts-fail-on-macOS surprises. The ranked "what is eating my disk" workflow is in find the largest files on disk.
Find files modified in the last N days
Pick a window from the Modified within dropdown above. The dropdown shows the find expression each option maps to (the time reference table explains the syntax).
find :search_path -type f :time_filterTo find files older than a window and delete them (typical cleanup script), flip the leading - in the expression to +. The inverse direction, for stale-file detection, is covered in find files not modified since:
find :search_path -type f -mtime +30 -deleteSubtle macOS difference: BSD find -mtime -N rounds the time differently than GNU. GNU rounds the file's age down to 24-hour units; BSD treats fractional days differently in some edge cases. For scripts that need exact behavior, use -newerXY (BSD) or -mmin (both) with explicit minutes.
Find files by owner or permission
find :search_path -type f -perm 0644Find anything world-writable (security hygiene check):
find :search_path -xdev -type f -perm -o+w 2>/dev/nullFind files owned by a specific user:
find :search_path -user www-data -type fExclude a directory from find
find . -path './node_modules' -prune -o -type f -print prints every file while skipping node_modules entirely. It looks odd, but every piece is load-bearing:
find :search_path -path './node_modules' -prune -o -type f -printRead it as two branches joined by -o (OR): if the path matches, prune it; otherwise, if it is a regular file, print it.
-prunetells find "do not descend into this path" and always evaluates to true, so the short-circuit OR never runs the keep branch fornode_modulesitself.- The
-ois mandatory. Without it the expression is an implicit AND (path matches AND prune AND type f AND print), which only ever prints things inside the pruned directory. - The trailing
-printis what keepsnode_modulesitself out of the output.-prunedoes not switch off find's implicit-print(only actions such as-exec,-deleteor-printdo). So without an explicit-print, find wraps the whole expression in one:find . -path './node_modules' -prune -o -type fstill lists every file, but it also prints./node_modules, because the prune branch is true for that path. Putting-printon the keep branch prints only what that branch matches.
To exclude several directories, group the -path tests in escaped parentheses (bare ones open a subshell) and prune the group:
find :search_path \( -path './node_modules' -o -path './.git' -o -path './dist' \) -prune -o -type f -print-path matches the whole path string from the search root. After find ., paths look like ./node_modules/foo, so the test needs the ./ prefix; after find /var/www, it needs /var/www/node_modules. A bare -path 'node_modules' matches nothing. To match the directory at any depth, use -path '*/node_modules'.
-prune vs -not -path
The readable alternative is a negated test:
find :search_path -type f -not -path '*/node_modules/*'No -prune, no -o, and the implicit print still applies because everything is a test. The catch: -not -path is a filter, not a skip. find still opens and stats every file inside node_modules, then discards them. -prune never opens the directory at all.
| Tree | -prune | -not -path |
|---|---|---|
| Small project, no big subtree | Same | Same |
Project with a 40k-file node_modules | Skips the subtree, fast | Walks all 40k files, then filters |
| Repeated in a watch loop or CI step | Cheap every run | Pays the full walk every run |
| Network or FUSE filesystem | Avoids slow stat calls | Triggers a stat per file |
For a one-off interactive command I type -not -path. For a file watcher, pre-commit hook, CI step or network mount I use -prune. Both forms, and the implicit-print behavior, are the same on BSD and GNU find. Other traps: put the prune branch before the -o (after it, find has already descended), never prune the search root itself (find node_modules -path 'node_modules' -prune returns nothing), and do not use -prune to exclude files; -not -name '*.min.js' is the tool for that. If the job is "search project files", fd, rg and git ls-files already honor .gitignore.
Run a command on every match
-exec runs a command for each match. The {} placeholder is replaced with the path; the command must end with \; (escaped semicolon).
find :search_path -type f -name ':pattern' -exec grep -l 'ERROR' {} \;Replace \; with + to batch arguments into fewer command invocations (much faster on large trees):
find :search_path -type f -name ':pattern' -exec grep -l 'ERROR' {} +-execdir runs the command in the directory of the matched file. Safer when paths have spaces or weird characters because the {} is just the basename:
find :search_path -type f -name ':pattern' -execdir rm {} \;-delete is the shortest destructive action. It has no confirmation and no dry run; the safe way to use it is in Find and delete files. For the full -exec versus xargs trade-off and parallel runs with xargs -P, see find and xargs in parallel.
Pipe find safely into another command
find ... | xargs command looks innocent but breaks the moment a filename contains a space, newline, or quote. The fix is NUL-delimited output: -print0 from find, -0 on xargs.
find :search_path -type f -name ':pattern' -print0 | xargs -0 gzipWhy this matters: filenames on Unix can contain literally any byte except / and NUL. -print separates with newlines, but newlines are valid in filenames. The only safe separator is NUL (\0). The same principle drives the tar (--null) and rsync (--from0) pipelines further down.
This pattern is the safe equivalent of find ... -exec cmd {} +, useful when you need shell features (piping, redirection) that -exec cannot give you. It pairs with the grep cheat sheet for the most common find-then-grep pipelines.
Find and delete files
find /path -type f -name '*.bak' -delete deletes every match with one command. There is no confirmation, no -i mode, no trash bin and no undo, so the only safe pattern is: write the command with -print first, read the list, then swap -print for -delete.
# Step 1: dry run
find :search_path -type f -name ':pattern' -print
# Step 2: same command, one word different
find :search_path -type f -name ':pattern' -deleteIf you are nervous, count first: find ... -print | wc -l. The same two-step works for any filter: -mtime +30 for stale files (clearing /tmp/cache, rotating log archives), -size +100M for oversized core dumps and build artifacts. For empty directories left behind, use the two-pass cleanup.
-delete vs -exec rm vs xargs rm
Four ways to delete matched files, in the order I reach for them:
find ... -delete: fastest, built in, handles weird filenames safely. Default for simple deletes.find ... -exec rm -v {} +: same speed, batches arguments, and gives yourmflags like-v(verbose, so you can log what went) or-f.find ... -print0 | xargs -0 rm -f: same speed, for when the delete needs shell features around it. Needs the NUL form on both sides.find ... -exec rm {} \;: forks onermper match. On 100,000 matches that is 100,000 forks. Avoid unless the command can only take one argument.
For a confirmation per file, use -exec rm -i {} \;. To move files somewhere instead of deleting them, -exec mv {} /path/to/trash/ \; or trash-cli. For all-or-nothing behavior, write the list first with find ... -print0 > /tmp/del-list, then xargs -0 rm -f < /tmp/del-list.
Delete mistakes that bite
- Actions before tests. find evaluates left to right, so
find . -delete -name '*.bak'deletes everything, because-deleteruns before the name filter. Tests first, actions last. - No
-type f. Without it, a directory calledsomething.bakmatches too, fails to delete because it is not empty, and floods you with errors. - Unanchored paths. Never point a
-deleteat/or~; a typo in the pattern matches more than you think. Anchor at a specific subdirectory, and skipsudounless the files genuinely need root. - Symlinks.
-deleteon a matched symlink removes the link, not its target. - Permission errors. A directory containing files you cannot delete keeps those files, then the directory delete fails. Run
-printfirst, or use-exec rm -fto surface the errors. Both GNU and BSD find continue past a failed delete and exit 1.
rm -rf /path is the right tool for "remove this whole tree" (and faster, since it evaluates nothing). find ... -delete is for "remove only what matches".
Archive find results with tar
find selects the files, tar packs them. The safe glue is a NUL-delimited list read from stdin:
find :search_path -type f -name ':pattern' -print0 | tar --null -czf archive.tar.gz --files-from=-| Flag | Side | What it does |
|---|---|---|
-print0 | find | Emit each path followed by a NUL byte instead of a newline |
--null | tar | Tell tar the incoming list is NUL-delimited |
--files-from=- | GNU tar | Read the list of files from stdin (-) |
-T - | BSD tar | Same as --files-from=-; BSD tar's spelling |
-czf | tar | Create, gzip, write to the next argument (-f must be last in the cluster) |
macOS ships bsdtar (libarchive) as /usr/bin/tar, which has no --files-from. GNU tar accepts -T as a synonym, so -T - plus --null is the portable spelling for scripts that run on both. --null and -print0 are a matched pair: forget --null and tar reads the whole stream as one giant filename.
Archive by time by composing any find test, for example everything changed in the window set above:
find :search_path -type f :time_filter -print0 | tar --null -czf archive.tar.gz -T -tar stores whatever path string find hands it. Run cd /var/log && find . -type f ... so the archive is rooted cleanly; find /var/log ... stores var/log/... and GNU tar strips the leading / with a warning. Check contents with tar -tzf archive.tar.gz, extract with tar -xzf archive.tar.gz -C /tmp/restore.
Appending with -exec, and compression choices
find . -type f -name '*.log' -exec tar -rvf logs.tar {} + appends batches to an archive, but append mode needs a seekable file, and a gzip stream is not one. Build the uncompressed .tar first, then gzip logs.tar as a separate step.
| Compressor | tar flag | Speed | Ratio | Notes |
|---|---|---|---|---|
| gzip | -z | Fast | Moderate | Universal, the safe default |
| bzip2 | -j | Slow | Better than gzip | Largely superseded by xz and zstd |
| xz | -J | Slowest | Best ratio | Great for archives you store and rarely touch |
| zstd | --zstd | Very fast | Near xz at high levels | Best speed-to-ratio balance; needs a recent tar |
I use -z for routine log bundles and --zstd for long-term storage or slow links. tar is an archiver, not a backup system, and for a Windows recipient zip is the safer format. On Windows itself:
Get-ChildItem -Path . -Recurse -File -Filter '*.log' | Compress-Archive -DestinationPath archive.ziprsync only the files find selected
rsync has name, size and path filters but no "modified in the last N days" filter. find has exactly that, so let find pick the files and feed the list to rsync. Keep the n in -avn (a dry run) until the output looks right, then drop it:
cd :search_path
find . -type f :time_filter -print0 | rsync -avn --files-from=- --from0 ./ user@host:/backup/--files-from=- makes rsync transfer only the listed entries, read from stdin. --from0 says the list is NUL-delimited, the matched pair for -print0: use both or neither.
The gotcha that breaks it every time: paths in the list are resolved relative to the rsync source argument. find . prints ./logs/app.log, the source is ./, they agree. Run find /var/www ... with ./ as the source and rsync looks for ././var/www/index.php, prints link_stat ... failed: No such file or directory for every entry, and copies nothing. The clean pattern is the one above: cd into the directory, find ., source ./.
For a precise "since the last backup" window, use a marker file instead of -mtime:
touch -t 202604010000 /tmp/since
find . -type f -name '*.sql' -newer /tmp/since -print0 | rsync -avn --files-from=- --from0 ./ user@host:/dest/--files-from also takes a hand-written, newline-delimited manifest: rsync -avn --files-from=manifest.txt ./ user@host:/dest/ (no --from0).
You do not need find when rsync can express the selection itself: --include='*/' --include='*.log' --exclude='*' for extensions (the */ include lets rsync descend into subdirectories, which the trailing * exclude would otherwise skip whole; add -m to drop the directories that end up empty), --max-size=1M / --min-size=10k for size, --exclude='node_modules/' for subtrees, and rsync already skips files whose size and mtime match the destination. If the word "when" or "modified" appears in the requirement, reach for find. Dry-run anything with --delete in it without exception, and remember a selective rsync is a transfer, not a backup; see off-server backups for that.
| Era | What macOS shipped | --files-from / --from0 |
|---|---|---|
| macOS up to Sonoma (14) | GNU-derived rsync, frozen at 2.6.9 (2006) | Supported, but ancient and buggy |
| Sequoia 15.0 to 15.3 | openrsync (a BSD-licensed rewrite), with the old 2.6.9 kept as a fallback | Depends on which binary handles the call; check rsync --version |
| Sequoia 15.4 onward (incl. Tahoe) | openrsync only | Current macOS openrsync documents both --files-from and --from0 |
| Homebrew (any macOS) | Current upstream rsync 3.x | Full support |
On macOS I brew install rsync and confirm with rsync --version. Windows has no native rsync: use WSL, or robocopy with /MAXAGE for an age-based copy.
macOS BSD vs GNU find
The divergences that matter, in order of how often they bite.
| Feature | GNU find | BSD find (macOS default) |
|---|---|---|
-regextype | Supported (-regextype posix-extended, etc.) | Not supported, errors out; use find -E |
-regex default flavor | Emacs regex | Basic POSIX (BRE); extended with -E |
-printf | Supported (rich format strings) | Not supported; use -exec stat |
-mtime / -mmin rounding | Both floor to whole units | -mtime floors in practice (the man page says it rounds up); -mmin rounds up to the next minute |
-iregex | Supported | Supported, but different default flavor |
-not operator | Supported | Supported (! also works) |
-prune, -path, -empty, -depth | Supported | Supported, same meaning |
-delete (implies -depth) | Same | Same |
GNU long options (--help, etc.) | Supported | Not supported on most options |
Why two finds at all: POSIX standardizes a baseline (-name, -type, -size, -mtime, -perm, -print, -exec, the boolean operators) and leaves every implementation free to add extensions. GNU findutils added a large set over the decades, BSD added its own overlapping but not identical set, macOS inherits the BSD lineage, and Linux distributions ship GNU. A script that uses a GNU-only extension runs fine on a Linux CI runner and dies on a MacBook.
-printf and the stat format strings
The single most common cross-platform script failure is -printf on macOS, which fails with find: -printf: unknown primary or operator. The BSD workaround is -exec stat, which forks one stat per file and is slower on big trees:
find :search_path -type f -printf '%s %p\n' | sort -rn | head -20That trades one divergence for another, because stat itself speaks two different format languages: GNU stat -c (or --format) against BSD stat -f, with different letters.
| What you want | GNU stat (Linux) | BSD stat (macOS) |
|---|---|---|
| File size in bytes | stat -c '%s' file | stat -f '%z' file |
| File name | stat -c '%n' file | stat -f '%N' file |
| Modification time (epoch) | stat -c '%Y' file | stat -f '%m' file |
| Octal permissions | stat -c '%a' file | stat -f '%Lp' file |
| Owner user name | stat -c '%U' file | stat -f '%Su' file |
The epoch-timestamp listing follows the same split: GNU -printf '%T@ %p\n' against BSD -exec stat -f '%m %N' {} \;.
Regex flavor, long options, and time boundaries
-regex. GNU defaults to the Emacs flavor and offers-regextype; BSD uses basic POSIX and rejects-regextype(usefind -E, covered in the regex section). In a script meant for both, I skip-regexentirely and filter downstream withgrep -E, which is POSIX extended on both:find . -type f -name '*.log' | grep -E '/[0-9]{4}-[0-9]{2}\.log$'.- Long options.
find --versionandfind --helpwork on Linux; BSD find rejects them, and its documentation lives inman find. A CI step that logsfind --versionbreaks on macOS, so identify the platform withunameinstead of asking find about itself. - Exact time cutoffs. When the
-mtimerounding difference in the table above matters, compare against a marker file instead;-newercompares exact mtimes on both:touch -t 202605120000 /tmp/cutoffthenfind . -type f ! -newer /tmp/cutoff.
Writing find scripts that run on both
Three strategies, in the order I reach for them.
1. Stick to the portable subset. If your shell scripts need to run on both Linux and macOS, stick to the POSIX-ish intersection: -name, -iname, -type, -size, -mtime, -mmin, -perm, -newer, -path, -prune, -empty, -print, -print0, -exec, -execdir, -delete, -maxdepth/-mindepth. Everything outside that set risks BSD/GNU drift; the known offenders are -printf, -regextype, -regex (default-flavor dependent), the -newerXY letter variants and GNU long options.
2. Detect the platform and branch when a script genuinely needs -printf-style output:
if [ "$(uname)" = "Darwin" ]; then
find . -type f -exec stat -f '%z %N' {} \; | sort -rn | head
else
find . -type f -printf '%s %p\n' | sort -rn | head
fi3. Require GNU findutils. Install it via Homebrew and call gfind explicitly. Homebrew adds a g prefix so the GNU tools do not shadow the system BSD versions: gfind and gxargs from findutils, gstat from coreutils.
brew install findutils
alias find='gfind'
alias xargs='gxargs'Aliases only affect interactive shells; a script run with #!/bin/bash does not see them, so it must call gfind by name. I prefer to leave the system find alone and call gfind deliberately where I need it, because aliasing find globally can surprise tools that expect BSD behavior on macOS. None of this matters for a single-platform script, a CI job pinned to ubuntu-latest, or a one-off command typed at the prompt: write to whichever find you have and keep the extensions.
find vs locate vs mlocate
find walks the live filesystem on every run: always current, but slow on a big tree. locate queries a database built earlier by updatedb: answers in milliseconds, but only as fresh as the last build (typically a daily cron job or systemd timer).
# find: walks the live filesystem now
find / -name 'nginx.conf' -type f 2>/dev/null
# locate: queries the prebuilt database (instant)
locate nginx.conf
# rebuild the database now (needs root)
sudo updatedb| Property | find | locate / mlocate | plocate |
|---|---|---|---|
| Freshness | Always current | Stale until next updatedb | Stale until next updatedb |
| Speed on large trees | Slow (full walk) | Fast | Very fast |
| Searches | Name, type, size, time, perms, content via -exec | Path name only | Path name only |
| Permission-aware | Yes (sees what the calling user sees) | Yes (mlocate/slocate); GNU locate no | Yes |
| Can filter by size / time / perm | Yes | No | No |
| Can run a command on matches | Yes (-exec, -delete) | No (pipe to xargs) | No (pipe to xargs) |
| Default on modern Debian/Ubuntu | Always present | Before Debian 12 / Ubuntu 22.04 | Debian 12+, Ubuntu 22.04+ |
"locate" is a lineage. GNU locate (findutils) leaked filenames from directories a user could not read. slocate added permission filtering and is largely historical. mlocate ("merge locate") was the long-time default on Debian, Ubuntu, Fedora and RHEL; its updatedb reuses the old database and re-stats only changed directories. plocate uses a compressed posting-list index, is dramatically faster, and is what locate points at on Debian 12+ and Ubuntu 22.04+. The query syntax is largely compatible, with one difference that bites: given several patterns, plocate returns only paths matching all of them, while mlocate returns paths matching any of them (unless you pass -A). /etc/updatedb.conf controls what is indexed (PRUNEPATHS, PRUNEFS), so check it before assuming the database is broken.
On macOS the database is not built by default (a fresh query says "database too small" or returns nothing), and I use mdfind instead: Spotlight keeps its index continuously current and can search content as well as names.
Use find when correctness matters, for files created since the last updatedb, for size/time/permission filters, for acting on matches, and in every script (a minimal container may have no locate database at all). Use locate/plocate for interactive "where does nginx.conf live" recall on a huge box, especially across repeated queries. For interactive search with friendlier defaults, fd walks the live tree in parallel and respects .gitignore (apt install fd-find, where the binary is fdfind, or brew install fd). To search file contents, use grep -r or ripgrep.
Find where a command is installed
find locates files; to ask where a command lives, use command -v ssh. It is a POSIX shell builtin, returns the path the shell would actually run, and sets a clean exit code. Use type for the full story (alias, function, builtin or file), and avoid which.
command -v ssh
# /usr/bin/ssh
type ssh
# ssh is /usr/bin/ssh
which ssh
# /usr/bin/ssh (usually, but see below for why "usually" is the problem)
Why which is the wrong default
which is an external program (typically /usr/bin/which), so it cannot see aliases, shell functions or builtins. It is not specified by POSIX, and implementations diverge: Debian's debianutils shell script, the GNU C program, a BSD version on macOS, and zsh/tcsh builtins that behave differently again. Some variants return success even when the command is missing. Debian's debianutils 5.0 (August 2021) deprecated its which and printed a warning steering users to command -v. The deprecation did not last: after a Debian Technical Committee ruling, 5.6-0.1 (January 2022) reverted it, so which still ships. The episode is a fair summary of how unsettled which is.
command -v in scripts
command -v ssh # /usr/bin/ssh (external command -> absolute path)
command -v cd # cd (builtin -> just the name)
command -v ll # alias ll='ls -alF' (alias -> the alias text)
if ! command -v jq >/dev/null 2>&1; then
echo "This script needs jq. Install it and re-run." >&2
exit 1
fiThe install guard works unchanged in dash, bash, zsh and BusyBox sh, and ShellCheck flags the if which foo form when you enable its optional deprecate-which check (SC2230, off by default). Test the exit code, not the printed text. command -V (capital V) prints a human-readable sentence instead.
type for debugging
type -a python3 # ALL matches, in resolution order
# python3 is /usr/local/bin/python3
# python3 is /usr/bin/python3
type -t git # just the kind: alias | keyword | function | builtin | file
# file
type -p git # path only, and ONLY if it resolves to a file on disk
# /usr/bin/gitWhen the wrong python3 runs, type -a shows the shadowing entry. Here is where the tools disagree:
alias grep='grep --color=auto'
command -v grep
# alias grep='grep --color=auto'
type -a grep
# grep is aliased to `grep --color=auto'
# grep is /usr/bin/grep
which grep
# /usr/bin/grepwhich never learns the alias exists, so it points you at the wrong answer. -a, -t and -p are bash extensions; bash's type -P forces a PATH search and prints a path even when a builtin or alias would match. If a command still resolves to an old path after an install, run hash -r. whereis answers a different question (binaries, sources and man pages by filename convention). My rule: command -v in scripts, type -a at the prompt, which never.
Common find gotchas
1. Forgetting to quote the pattern. find . -name *.log lets the shell expand *.log first. If a matching file exists in the current directory, that gets passed as the pattern; if none does, you get a confusing "paths must precede expression" error. Always quote: find . -name '*.log'.
2. -print is unsafe in pipelines. Filenames with spaces or newlines break xargs by default. Use -print0 | xargs -0 for any pipeline that handles arbitrary paths.
3. The -exec ... {} \; semicolon is shell metacharacter. Always escape with backslash or quote: \; or ';'. Without it, the shell ends the find command at the semicolon.
4. -exec ... {} + versus -exec ... {} \;. The + form batches arguments into a single command invocation (fast). The \; form forks once per match (slow on large trees). Use + unless the command can only accept one path at a time.
5. Deleting directories without -depth. Parents are evaluated before children, so nested empty trees survive. find . -depth -type d -empty -delete collapses them; see Find empty directories.
6. -maxdepth and -mindepth must come BEFORE other tests. Putting them after -name or -type is technically legal but evaluated left to right, which can produce surprising results. Place depth restrictions first.
7. -name matches the basename only, not the path. find . -name 'src/*.ts' will never match because the slash makes it a path, not a basename. Use -path '*/src/*.ts' instead. -regex is the opposite: it must match the whole path.
8. Explicit actions switch off the implicit -print. Any -exec, -delete or -print0 in the expression means you must add -print yourself where you want output. -prune is the exception: it leaves the implicit print on, which is why a prune expression without -print also lists the pruned directory.
9. find / with no filters scans the whole filesystem. Including network mounts, /proc, /sys. Always scope with a real start path or add -xdev to stay on one filesystem.
What to do next
Deep dives by task:
- Find files not modified since N days: the
-mtime +Ndirection, for stale-file detection - Find the largest files on disk: the ranked "what is eating my disk" workflow
- Find files by owner or permission:
-user,-perm, and the SUID/world-writable audits - Run find in parallel with xargs -P:
-execvsxargs, and the parallelism deep-dive - Search file contents recursively: the most common find-then-grep job
Related cheat sheets:
- grep cheat sheet: the classic pairing for find.
find ... -print0 | xargs -0 grepis one of the most common pipelines. - SSH cheat sheet: for running find against remote hosts.
- curl cheat sheet: for downloading lists of files that find generates.
- Bash for loop: when you need to loop over find output with logic that does not fit in
-exec. - Bash while loop: the safe
while IFS= read -r -d '' file; do ...; done < <(find ... -print0)pattern for processing files line by line. - Bash functions: where
command -vinstall guards usually live. - How to zip multiple directories into individual files: a worked example of
find ... -print0 | xargs -0 zip. - How to increase Google Cloud VM disk size without rebooting: uses
findfor the cleanup pass before resizing. - External: GNU findutils manual, FreeBSD find(1), GNU tar manual, rsync(1), plocate, PowerShell Get-ChildItem.
FAQ
-printf is a GNU extension and BSD find does not support it. The macOS workaround is to call stat for each match: find . -type f -exec stat -f '%z %N' {} \;. The BSD stat uses different format codes than GNU stat, so this is one of the most platform-specific corners of shell scripting.
If a script needs the same behavior on both, install GNU findutils via Homebrew (brew install findutils) and use gfind -printf. Or detect the platform with uname and branch.
Run brew install findutils. Homebrew installs the GNU tools with a g prefix so they do not shadow the system BSD versions: gfind and gxargs. For GNU stat, install coreutils, which provides gstat. Aliases such as alias find='gfind' only affect interactive shells, so a script that needs GNU find must call gfind explicitly.
-exec ... {} + and find -print0 | xargs -0 do roughly the same thing: batch matched paths into one command invocation. -exec is built into find, requires no second tool, and handles weird filenames safely. xargs is more flexible because it can use shell features (pipes, redirection, conditional logic).
Use -exec ... {} + when the command is simple. Use find -print0 | xargs -0 ... when you need shell pipelines, environment variables, or anything xargs can do that -exec cannot.
Use -mmin for minute-resolution time: find . -type f -mmin -60 matches anything modified less than 60 minutes ago. The negative sign means "less than"; +60 would mean "more than 60 minutes ago".
For exact time windows, combine with -newer FILE: touch -t 202605170900 /tmp/mark; find . -newer /tmp/mark -type f finds anything modified since 9 AM today. This avoids the rounding subtleties of -mtime.
Join the -name tests with -o and wrap them in escaped parentheses: find . -type f \( -name '*.jpg' -o -name '*.png' \). The parens are mandatory. Without them, the implicit AND binds tighter than -o, so -type f applies only to the first extension and directories leak into the second branch.
-name matches against the basename of each path, not the full path. A slash in the pattern means it can never match a basename (basenames never contain slashes).
Use -path '*/src/*.ts' to match against the full path. Or combine -name '*.ts' with a -path or -prune filter for the directory. The find . -path '*/node_modules/*' -prune -o -name '*.ts' -print pattern is the standard way to exclude a subtree.
Because -regex matches against the entire path string that find is evaluating, not the basename and not a substring. find is testing paths like ./notes/todo.txt, and the pattern .txt only describes a three-character string.
Prefix the pattern with .* so it soaks up the leading directories: .*\.txt reads as "any path ending in a literal .txt". On Linux add -regextype posix-extended before it if you use groups or alternation; BSD find on macOS rejects that flag, so use find -E (before the path) there instead.
Strictly it does not: -prune is exempt from the rule that explicit actions switch off find's implicit -print, so find . -path './node_modules' -prune -o -type f still lists every file. The catch is that the implicit print wraps the whole expression, and the prune branch is true for ./node_modules, so the pruned directory name is printed too.
Putting -print (or -print0, or -exec) on the keep branch limits output to what that branch matches, which is why I always write it.
Because it is not actually empty. A directory counts as empty only when it has zero entries, and a hidden file is still an entry. A folder holding a single .gitkeep, .DS_Store, or .env is non-empty, and so is a folder that contains one subdirectory, even an empty one. Run ls -la on the directory to see the hidden entries.
Filter with -type f: find /tmp -type f -name '*.bak' -delete. Without -type f, find would also try to delete directories matching the name, which fails with a non-empty-directory error.
Critical safety habit: always run the command with -print first to verify what would be deleted, then swap -print for -delete. find -delete has no confirmation and no undo. To also remove the directories that are now empty, run a second pass: find /tmp -depth -type d -empty -delete.
Usually not. find -delete calls unlink() on each file, which removes the directory entry. On ext4, btrfs, and most modern filesystems, the inode and data blocks are freed and may be overwritten at any time. Recovery tools like extundelete or photorec can sometimes pull back recently-deleted files, but only if the underlying blocks have not been reused.
The reliable safety net is backups, not recovery. Before a destructive cleanup on a server, snapshot first if your filesystem (ZFS, btrfs) or storage layer (cloud disk snapshot) supports it.
No. tar -r (append) needs to seek to the end of the archive, and a gzip stream is not seekable. You can only append to an uncompressed .tar. Build or update it with find . -name '*.log' -exec tar -rvf logs.tar {} +, then compress it with gzip logs.tar as a separate final step.
Almost always a path mismatch. Paths in the list are resolved relative to the rsync source argument. If find prints ./logs/a.log the source must be ./; if find prints absolute paths like /var/www/a.php the source must be /. Mismatch them and rsync reports failed: No such file or directory for every entry and transfers zero files.
The fix: cd into the directory, run find ., and pass ./ as the source so the list paths and the source agree.
find walks the live filesystem every time it runs, so its results are always current but can be slow on a large tree. locate queries a prebuilt database created by updatedb, so it returns in milliseconds but only reflects the filesystem as of the last database build.
Use find when you need accuracy, recent files, or filters like size and time, and always in scripts. Use locate (on recent Debian and Ubuntu, that is plocate) for fast interactive lookups by name when day-old data is acceptable.
Use command -v. It is part of the POSIX standard, it is a shell builtin so it sees aliases and functions, and it sets a reliable exit code (0 if the command resolves, non-zero if not). which is an external program that is not specified by POSIX, varies between distros, and on some systems returns success even when the command is missing. The standard install-guard idiom is if ! command -v jq >/dev/null 2>&1; then ...; fi.
Bash remembers (hashes) the location of a command the first time it runs it in a session, so it does not re-search PATH every time. Install a newer binary into a directory earlier on your PATH and the shell can keep running the stale one until you clear that cache. Run hash -r to forget all remembered locations, or hash -d name to forget one. After that, type name and command -v name report the new path.
Use -xdev (or its synonym -mount): find / -xdev -type f -size +100M. This stops find from crossing into mounted filesystems, which is essential when scanning a server with NFS mounts, network shares, or container overlay filesystems.
Without -xdev, scanning / can recurse into /proc, /sys, network mounts, and any user-mounted filesystem, taking far longer and producing irrelevant results.
PowerShell's Get-ChildItem (alias gci or ls) is the closest equivalent. The -Recurse, -Filter, -Include, and -File/-Directory parameters cover most find use cases. Pipe through Where-Object for size, time, or attribute filters.
On Windows 10 and later, WSL gives you the real GNU find command. Git for Windows also ships a Bash environment with GNU find available. The CMD where command is NOT a find replacement; it only searches PATH for executables.
Pipe to wc -l: find . -type f -name '*.log' | wc -l. Caveat: this fails for filenames containing newlines. The safe version is find . -type f -name '*.log' -printf '.' | wc -c on GNU, or find . -type f -name '*.log' -exec printf '.' \; | wc -c on BSD.
For most real-world filesystems, the simple | wc -l is fine. Reach for the safe form only when processing untrusted input or filenames you do not control.
Sources
Authoritative references this article was fact-checked against.
- GNU project documentationgnu.org
- rsync(1) man page (Samba/rsync)download.samba.org
- GNU findutils manual (find)gnu.org
- POSIX.1-2017 command utility specification (The Open Group)pubs.opengroup.org
- Bash Reference Manual: Bash Builtin Commands (type), GNUgnu.org
- which(1) Linux manual page (man7.org)man7.org
- Debian bug 992401: debianutils which deprecation warning (5.0.1-1)bugs.debian.org
- find(1), GNU findutils manual page (Debian)manpages.debian.org
- find(1), macOS 26.7 manual pageman.freebsd.org
- openrsync(1), macOS 26.7 manual pageman.freebsd.org
- macOS rsync to openrsync transition by release (Flutter issue 189645)github.com
- rsync(1) filter rules, RsyncProjectgithub.com
- plocate(1) manual page (Debian)manpages.debian.org
- Ubuntu 22.04 LTS (Jammy Jellyfish) release notesdiscourse.ubuntu.com
- debianutils Debian changelogsources.debian.org
- ShellCheck SC2230 (optional deprecate-which check)shellcheck.net
- GNU find: Emacs regular expression syntaxgnu.org





