Cheat Sheets

find Command Cheat Sheet: -exec, -delete, -prune, xargs (PDF)

This post contains affiliate links. If you buy through them, we may earn a small commission at no extra cost to you. Learn more.

find . -delete -name "*.tmp" doesn’t delete your temp files. It deletes the whole tree, because find evaluates its expression left to right and -delete is an action that fires the moment the walk reaches it. The name test after it never gets a say. Most find mistakes have the same shape: the command reads like English, but the expression is a short program with an evaluation order, rounding rules and precedence that English does not have.

Original content from computingforgeeks.com - post 197313

This find command cheat sheet puts the reference tables first, then follows each group through a scratch tree with known names, sizes, permissions and timestamps, so you can see exactly which files a test picks up and why. Everything below was run on Ubuntu 26.04 and Rocky Linux 10 (both on GNU findutils 4.10.0) in November 2026, with Ubuntu 24.04 (findutils 4.9.0) as a second Ubuntu and FreeBSD 15.1 as the BSD reference.

find cheat sheet: the quick reference

Every row below ran against the lab tree, and each one is a complete command you can paste. Quote every glob you hand to -name, because the shell expands an unquoted *.log before find sees it whenever the current directory happens to hold a matching file. For the everyday file commands you’ll pair with find, the Linux commands cheat sheet for Ubuntu and Rocky Linux covers them in the same tested format.

Match by name and path

CommandWhat it does
find . -name "*.log"Base name matches the glob (case-sensitive)
find . -iname "readme*"Same, ignoring case
find . -maxdepth 1 -name "*.conf"Current directory only, no recursion
find . -mindepth 2 -name "*.conf"Skip the top level
find . -path "*/cache/*" -name "*.tmp"Glob against the whole path
find . -name "*.log" -not -name "debug*"Exclude a name
find . -regextype posix-extended -regex ".*/app-[0-9]{1}\.log"Extended regex on the full path (GNU)
find . -name "*.log" -print -quitPrint the first match and stop
find -name "*.conf"GNU only: no path means the current directory

Match by type and size

CommandWhat it does
find . -type d -name logsDirectories only
find . -type lEvery symlink, working or broken
find . -xtype lBroken symlinks only (GNU)
find -L . -type lBroken symlinks, works on GNU and BSD
find . -type f -size +10MFiles larger than 10 MiB
find data cache -type f -size -1024cUnder 1024 bytes, counted exactly
find . -emptyEmpty files and empty directories
find . -type f -size +1M -exec ls -lh {} +Large files with human sizes

Match by modification time

CommandWhat it does
find logs -type f -mtime +30Modified more than 30 full days ago
find logs -type f -mtime -7Modified within the last 7 days
find logs -type f -mmin -180Modified within the last 180 minutes
find logs -type f -newer logs/app-2.logNewer than a reference file
find logs -type f -newermt "2026-11-01" ! -newermt "2026-11-25"Modified between two dates
find logs -daystart -type f -mtime 0Modified since midnight (GNU)
find logs -type f -mtime +30 -lsOld files with an ls -dils style line
find logs -type f -printf "%TY-%Tm-%Td %TH:%TM %s %p\n"Date, size and path per file (GNU)

Match by permissions and owner

CommandWhat it does
find bin -type f -perm 755Mode is exactly 755, nothing more
find . -type f -perm -u+xAll listed bits are set
find . -type f -perm /o+wAny listed bit is set (world-writable)
find . -type f -perm -4000SUID files
find /usr/bin -xdev -type f -perm -4000SUID binaries, one filesystem only
find . -user kenneth -name "*.env"Owned by a given user
find . -type f -perm 600 -printf "%m %u:%g %p\n"Mode, owner and path (GNU)
find . -type f -perm /o+w -exec chmod o-w {} +Strip world-write in one pass

Run commands: -exec and xargs

CommandWhat it does
find logs -name "*.log" -exec echo run {} \;One process per file
find logs -name "*.log" -exec echo run {} +Batch many files into one process
find . -name "*.conf" -exec grep -l "listen 443" {} +Files whose content matches
find src -name "*.py" -execdir pwd \;Run from the file’s own directory
find cache -name "*.tmp" -ok rm {} \;Ask y/n before each command
find logs -name "*.log" -print0 | xargs -0 ls -lNUL-separated, safe with spaces
find logs -name "*.log" -print0 | xargs -0 -n 2 echo batchAt most 2 names per command
find . -name "*.nomatch" -print0 | xargs -0 -r lsRun nothing when nothing matched (GNU)
find logs -name "*.log" -print0 | xargs -0 -P 4 gzip4 parallel workers

Delete safely

CommandWhat it does
find . -name "*.tmp" -printDry run: see exactly what would go
find . -name "*.tmp" -deleteDelete the same set, -delete last
find logs -type f -name "*.log" -mtime +30 -delete -printDelete and log each name
find . -type d -empty -delete -printRemove empty directories
find . \( -name "*.log" -o -name "*.tmp" \) -deleteGroup -o tests before the action

Prune and combine tests

CommandWhat it does
find . -path ./node_modules -prune -o -name "*.js" -printSkip one directory, print the rest
find . -name node_modules -prune -o -type f -name "*.js" -printSkip every directory with that name
find . \( -name .git -o -name node_modules \) -prune -o -type f -printSkip several directories
find . \( -name "*.py" -o -name "*.js" \) -printOR two tests, then act on both
find / -xdev -name "sshd_config" 2>/dev/nullStay on one filesystem, hide permission errors

Ubuntu 26.04 still runs GNU find

Ubuntu 26.04 replaced GNU coreutils with the Rust rewrite from uutils, and a lot of people assume find went with it. It didn’t. find and xargs live in the separate findutils package, and that package is still GNU. You can check which one you have in two commands, because dpkg -S names the package that owns the binary.

dpkg -S /usr/bin/find
find --version | head -1

On the test VM the binary belongs to findutils and identifies itself as GNU, while ls on the same box is the uutils build under /usr/lib/cargo/bin/coreutils/:

Ubuntu 26.04 terminal showing /usr/bin/find owned by the findutils 4.10.0 package while ls reports uutils coreutils 0.10.0

The uutils rewrite of find does exist in the archive, as the rust-findutils package in universe, but it isn’t installed by default and it doesn’t take over the name. It installs rust-find and rust-xargs, so plain find stays GNU even if you add it. Rocky Linux 10 is the same story through RPM: rpm -qf /usr/bin/find names the findutils package, built from the same upstream release as Ubuntu’s. That matters for this page in a practical way.

Everything in the GNU column below applies to both distros. On the lab tree the outputs matched row for row, apart from file order, permission bits from a different umask and the SELinux dot that Rocky’s ls -l appends. You will not need a separate command set for either one.

Time and size tests round first

-mtime +1 does not mean “older than one day”. GNU find divides a file’s age by 24 hours, throws away the fraction, and only then compares the whole number to your argument. The GNU manual says so directly, and the lab shows what it does to a file that’s 36 hours old.

Here are the six log files with their timestamps, followed by three age tests:

find -printf listing log mtimes, then -mtime -7, -mtime +1 and -mtime 1 showing the 36 hour old file matches -mtime 1 and -mtime -7 but not -mtime +1

Read the access 2026.log line. It was written 36 hours before the test, so its age is 1.5 days, which truncates to 1. That’s why it shows up for -mtime 1 and for -mtime -7, but not for -mtime +1: “+1” means a truncated age greater than 1, so in practice 48 hours or more. In order, the three forms mean:

  1. -mtime -7: truncated age 0 to 6, so less than 7 days
  2. -mtime 1: truncated age exactly 1, so 24 to 48 hours
  3. -mtime +1: truncated age 2 or more, so at least 48 hours

When you need hour precision, use -mmin instead: -mmin -180 matched only the two hour old app-3.log. For calendar ranges, -newermt takes a date string and skips the arithmetic entirely, and -daystart measures from midnight rather than from now.

The guide to finding files older than X days or minutes goes further into -mmin for cleanup jobs that run every few minutes.

Size has the same trap with a different unit. GNU find rounds a file’s size up to the unit you ask for before it compares, so -size -1k means “rounds up to less than one KiB”, and the only sizes that qualify are zero bytes. The tree has a 500 byte small.bin, which is plainly less than a kilobyte:

GNU find -size -1k matching only empty files while -size -1024c also matches the 500 byte small.bin

-size -1k returned the three empty cache files and missed small.bin. -size -1024c caught it, because c counts bytes and there’s nothing to round. Use the byte suffix whenever your threshold is small enough for rounding to matter. The larger units are fine where a few hundred bytes do not change the answer. FreeBSD compares plain bytes when you give a unit suffix, which the BSD section shows.

-perm has three matching modes

The prefix in front of the mode decides how find compares it, and getting it wrong usually returns nothing rather than an error. The three forms:

  • -perm 755: the mode equals 755 exactly
  • -perm -u+x: every listed bit is set, others don’t matter
  • -perm /o+w: at least one listed bit is set

The exact form is the one that will surprise you. The lab’s bin/ holds deploy.sh at 755 and a copy called suidtest at 4755, and the commands below show which test sees which file:

find bin -type f -perm 755
find . -type f -perm -u+x
find . -type f -perm -4000

Exact match drops suidtest because the SUID bit makes its mode 4755, not 755. The “all bits” form finds both, and -4000 finds only the SUID file. The output below is the three commands in order: one line, then two, then one:

bin/deploy.sh
./bin/deploy.sh
./bin/suidtest
./bin/suidtest

Run the same -perm -4000 test against /usr/bin with -xdev and you get the SUID audit you’d want on any server. Ubuntu 26.04 listed 11 binaries, passwd and su among them. Rocky 10’s list included pkexec. Compare your list against the one from a clean install, since a SUID binary you didn’t expect is the finding you’re looking for.

On the fixing side, -perm /o+w -exec chmod o-w {} + cleared the one world-writable file in the copy, and a second pass counted 0. Run that second pass every time you fix permissions in bulk, because it is the only proof the first one caught everything.

-exec + batches like xargs

The terminator you put after -exec decides how many processes find starts. With \; it runs your command once per file. With + it packs as many paths as fit onto one command line, the way xargs does.

Using echo makes the difference visible, and timing a harmless command over every .gz file in /usr/share makes it measurable. You can run both on any box without changing a thing:

find -exec with semicolon running once per file versus -exec plus batching, timed over 6208 gz files on Ubuntu 26.04

Five run lines against one tells you the batching works, and the timing tells you why it matters: 6.37 seconds against 0.05 seconds for the same 6208 files, a factor of about 125. The other two hosts told the same story with their own file counts:

Host.gz files under /usr/share-exec true {} \;-exec true {} +
Ubuntu 26.0462086.37 s0.051 s
Ubuntu 24.0456337.07 s0.068 s
Rocky Linux 1030144.71 s0.079 s

Rocky printed a Permission denied for /usr/share/empty.sshd during both runs, which is SSH’s privilege separation directory, so expect that line when you run this as a normal user there:

Rocky Linux 10.2 with findutils 4.10.0 and SELinux enforcing, timing find -exec semicolon against -exec plus

So when should you keep \;? In three cases, because + requires {} to sit right before it and always returns true:

  • The command accepts exactly one file per call
  • {} has to sit somewhere other than last, as in mv {} /backup/
  • The exit status is a test, as in -exec grep -q x {} \; -print

On Linux you can dodge the second case with mv -t /backup/ {} +, which names the target first so the batch can go last. Both GNU and uutils mv accept -t.

Pairing find with grep is the classic batch case. -exec grep -l "listen 443" {} + found src/tls.conf in one grep process, and the grep cheat sheet covers the flags you will want for that combination.

Two variants change where and whether your command runs. -execdir runs it from the directory that holds the file, so -execdir pwd \; printed /home/kenneth/lab/site/src twice, once per Python file.

-ok asks you first. Fed “y” then “n” on standard input, it prompted < rm ... /home/kenneth/lab/ok/cache/a.tmp > ?, removed a.tmp, kept c.tmp on the “n”, and kept b.tmp once the input ran out.

xargs splits on whitespace unless you say -0

Piping plain find output into xargs works until a file name contains a space, a quote or a newline. xargs reads its input as whitespace-separated words. One file called access 2026.log arrives as two arguments, and neither exists. Pair -print0 with xargs -0 and both sides switch to NUL separators, the one byte a Linux path can’t contain:

xargs splitting a file name with a space, the -print0 and xargs -0 fix, and xargs -r on empty input

The first pipeline printed ls: cannot access 'logs/access' and ls: cannot access '2026.log', listed the four files without spaces, and exited with status 123, which is how GNU xargs reports that a command it ran failed. The second listed all five. Check that exit code in your scripts, because the four good lines make the broken run look successful.

The bottom half of the screenshot is the quieter problem. When find matches nothing, GNU xargs still runs the command once with no arguments, so xargs -0 ls listed the current directory. With ls that’s noise; with a command whose no-argument behaviour does something real, it’s a bug. Add -r and the empty run printed nothing. The other flags people reach for:

  • -n 2: at most two names per command, which split five logs into batches of 2, 2 and 1
  • -P 4: four commands in parallel, which gzipped all five logs, including the one with a space
  • -r: skip the run when the input is empty

When the next step is text processing rather than file operations, the comparison of grep vs awk vs sed helps you pick the tool on the receiving end of the pipe.

-delete runs where you put it

find joins tests with an implicit AND and evaluates them left to right, stopping at the first false one. An action like -delete is just another term in that chain, and it returns true after it deletes. So -name "*.tmp" -delete deletes only what passed the name test.

Flip the two and -delete -name "*.tmp" deletes every path it reaches, then checks the name when it no longer matters. Want to see it? Run it on a copy, never on the original:

cp -Rp ~/lab/site ~/lab/trap
find ~/lab/trap | wc -l
find ~/lab/trap -delete -name "*.tmp"
ls -la ~/lab/trap

The tree had 41 entries. After the misordered command, there was nothing left to list, including the top directory itself:

find with -delete placed before -name removing all 41 entries of a scratch tree, followed by the safe -mtime +30 -delete -print form

Directories went too, which may surprise you if you know that -delete will not remove a non-empty directory. The reason is that -delete switches on -depth, so find visits a directory’s contents before the directory.

By the time it reaches each directory, everything inside is already gone, and the empty directory deletes cleanly. FreeBSD did exactly the same thing to its copy. The habit that prevents it:

  1. Run the expression with -print and read the list
  2. Replace -print with -delete, keeping it as the last term
  3. Add -print after -delete when you want a log of what went

Following those steps on a fresh copy, the dry run listed three .tmp files and the real run took the tree from 41 entries to 38. Did the logged form behave? -mtime +30 -delete -print removed and named the two 40 day old logs. It left the 90 day old .log.gz alone, because that name does not match -name "*.log".

For retention jobs built around this pattern, the walkthrough on how to find and delete files older than N days adds cron scheduling and per-directory rules.

-o binds looser than the action

AND binds tighter than OR in a find expression, and the implicit AND sits between every pair of terms. That means -name "*.log" -o -name "*.tmp" -delete parses as “logs, OR (tmp files AND delete)”. The action belongs only to the right side of the -o. What happens when you run both forms on a copy:

find -o precedence: ungrouped -print and -delete apply only to the second test, grouped parentheses apply to both

The first pair is the harmless version. With an explicit -print on the right, -name "*.py" -o -name "*.js" -print printed only the two JavaScript files, and grouping both tests in \( \) brought back all four.

The second pair is the same mistake with -delete. The ungrouped run removed the .tmp files and left all five logs in place. Nothing errors, so you’d only notice when the disk didn’t free up. The grouped run removed both kinds and the recount came back 0. Escape the parentheses (or quote them) and leave a space on each side, or your shell eats them.

-prune needs an explicit -print

-prune does not filter output. It returns true and tells find not to descend into the current directory, and that’s all it does. The idiom -path ./node_modules -prune -o ... -print works because the pruned directory takes the left branch of the OR, and only the right branch prints. Drop the -print and find adds an implicit one around the whole expression, so the pruned directory itself gets printed:

find -prune skipping node_modules with and without -print, and GNU find refusing -prune combined with -delete

With -print the output was just ./src/app.js; without it, ./node_modules appeared above it. Pruning .git and node_modules together cut the file count from 25 to 23, one file under each. On a real project those two directories are usually the bulk of the tree, so the prune is also the biggest speedup you have. Which form should you reach for?

  • -path ./node_modules -prune: one directory at one place
  • -name node_modules -prune: that name at any depth
  • \( -name .git -o -name node_modules \) -prune: several names at once

The last command in the screenshot is the dangerous combination. Because -delete turns on -depth, find has already walked into a directory before it gets the chance to prune it, so pruning cannot protect anything. GNU find refuses to run and says exactly that:

find: The -delete action automatically turns on -depth, but -prune does nothing when -depth is in effect.  If you want to carry on anyway, just explicitly use the -depth option.

It exits with status 1 and deletes nothing. When you need to delete everywhere except one directory, exclude it with -path tests instead of pruning, and dry run the exact expression with -print first. Whatever that list shows, including the excluded directory itself, is what -delete will try to remove. FreeBSD handles this case very differently, which is the strongest reason to read the next section before you copy a GNU one-liner to a BSD or macOS box.

BSD find accepts less and warns less

FreeBSD and macOS ship BSD find rather than GNU find, and Apple’s man page in its open source shell_cmds repository reads almost line for line like FreeBSD’s.

The FreeBSD rows below come from running the same tree on a FreeBSD VM; the macOS column comes from Apple’s find(1) man page source, not from a Mac. Several GNU habits fail outright on FreeBSD:

FreeBSD 15.1 find rejecting --version and -daystart, needing -E for extended regex, rounding -size -1k differently and silently ignoring -prune with -delete

Three lines in that capture deserve a second look, because each one changes what your script does without an error to warn you:

  • Plain -regex with + printed nothing; -E fixed it
  • -size -1k matched the 500 byte small.bin that GNU skipped
  • -prune with -delete ran silently and protected nothing

The regex result comes from BSD treating the pattern as a basic regex, where + is a literal. The last one is the one to remember. The follow-up search found no .py files left, including the two inside the src directory the command meant to protect.

BehaviourGNU find (Ubuntu, Rocky)FreeBSD (tested)macOS (Apple’s man page)
Path omittedDefaults to .illegal option -- nPath required in the synopsis
--versionPrints the versionillegal option -- -No long options listed
-regex flavourEmacs style, -regextype to changeBasic regex, -E for extendedBasic regex, -E for extended
-daystart, -xtypeSupportedunknown primary or operatorNot listed
-printfFull format setRuns; man page lists a subset with flags not yet implementedNot listed; use -exec stat -f
-perm /modeAny bit setWorks, alias for +modeOnly +mode listed
-size -1k on 500 bytesNo matchMatchSame size wording as FreeBSD
-prune with -deleteRefuses, exit 1Runs, deletes inside the pruned directoryMan page: -prune has no effect with -d
xargs with no inputRuns the command onceRuns nothingNot tested
-delete before the filterDeletes the treeDeletes the treeMan page warns it should come last

Time tests differ too, on paper. The FreeBSD and Apple man pages both say -mtime rounds a file’s age up to the next full 24 hours. The GNU findutils manual truncates it instead. A 36 hour old file is a “1” on GNU and, by that wording, a “2” on BSD, so boundary cases like -mtime 1 can disagree. The portable subset is smaller than most cheat sheets suggest:

  • Always pass a path, even .
  • Use -L -type l for broken links, which returned ./links/broken on all four systems
  • Use -print0 | xargs -0, -exec {} +, -mmin, -newermt and -quit, which behaved the same on both
  • Prefer byte thresholds (-size -1024c) when the exact cut-off matters

If a script has to run on both sides, install GNU findutils on the BSD host and call gfind and gxargs explicitly rather than guessing which flags survive. On FreeBSD that one change removes every row in the table above from your list of things to remember.

Expression order decides what runs

Nearly every failure on this page came from one fact: find reads its expression left to right and acts the moment an action is reached. This table is the order to write terms in, from left to right, and what goes wrong when one moves:

PositionTermsIf it is out of place
1. Options-L, then the path, then -maxdepth, -mindepth, -daystart, -xdevGNU warns about options after tests; BSD rejects a missing path
2. Prune-path ... -prune -oWithout the -o and an explicit action, the pruned directory prints
3. Cheap tests-type, -name, -pathSame result, but the costlier tests that follow run on more files
4. Expensive tests-mtime, -size, -perm, -newerRounding applies wherever they sit; check boundaries with -print
5. Grouped ORs\( a -o b \)Ungrouped, the action binds only to the last test
6. Action-print, -exec ... +, -deleteAn action before a test runs on everything the walk reaches

The rule that falls out of the table is short. Write the command with -print as the last term, read what it prints, then swap the action in. That habit would have saved the 41 entry tree in the trap test, and it costs you one extra command.

Want the shell, pipes and permissions around find at book length? William Shotts’ The Linux Command Line (third edition, No Starch Press) has a full chapter on searching for files. It is the book to hand anyone on your team who keeps reaching for the mouse.

Keep reading

Claude Code Cheat Sheet: Commands, Shortcuts and Flags (PDF) AI Claude Code Cheat Sheet: Commands, Shortcuts and Flags (PDF) OpenAI Codex CLI Cheat Sheet: Shortcuts, Commands, Flags (PDF) AI OpenAI Codex CLI Cheat Sheet: Shortcuts, Commands, Flags (PDF) Linux and DevOps Cheat Sheets (Free PDF Pack) Cheat Sheets Linux and DevOps Cheat Sheets (Free PDF Pack) netsh Commands Cheat Sheet: Wi-Fi, Firewall, Port Proxy (PDF) Cheat Sheets netsh Commands Cheat Sheet: Wi-Fi, Firewall, Port Proxy (PDF) VS Code Keyboard Shortcuts Cheat Sheet (Windows, Mac, Linux PDF) Cheat Sheets VS Code Keyboard Shortcuts Cheat Sheet (Windows, Mac, Linux PDF) Linux Commands Cheat Sheet for Ubuntu and Rocky Linux (PDF) Cheat Sheets Linux Commands Cheat Sheet for Ubuntu and Rocky Linux (PDF)

Leave a Comment

Press ESC to close