Finding Files with find, locate, and xargs
A practical guide to find (names, types, sizes, times, permissions, -prune, -exec and -delete), xargs for batch and parallel work, locate, and command lookup with type.
By The Dark DebuggerUpdated 28 min read
This article teaches find properly: selecting files by name, type, size, age and permissions, skipping directories, combining tests, and acting on the results with -exec, -delete and xargs. It also covers locate and the commands that find programs rather than files (type, which, command -v). You should know globbing and quoting from Wildcards, Globbing, and Brace Expansion and permission modes from File Permissions and Ownership. Next in the path is Variables, Quoting, and the Environment.
Why find is worth learning properly
Picture an alert at 3 a.m.: the disk on an application server is 95% full. You need to know which files are big, which are old, and which you can safely delete, across a directory tree with thousands of entries. ls and globs can't answer "every file over 100 MB, anywhere under here" or "every compressed log older than 30 days". find can, and it can delete, compress or change permissions on exactly those files in the same command.
The flip side is that find is one of the few everyday commands that can silently delete a whole directory tree because of the order of its arguments. We'll look at that trap directly, in a throwaway directory.
A practice directory
All examples run against a small, realistic application directory. truncate -s creates sparse files: they report a large size but use almost no disk space, which makes them perfect for practising size searches. touch -d sets a file's modification time to a date in the past, so the age tests have something to find.
mkdir -p ~/practice/find && cd ~/practice/find
mkdir -p app/{logs/archive,releases/{v1.4.0,v1.5.0},cache,node_modules/left-pad,.git}
mkdir -p 'app/uploads/Q3 reports'
printf '2026-11-09 03:00:01 INFO started\n' > app/logs/app.log
printf '2026-11-08 03:00:01 INFO started\n' > app/logs/app.log.1
touch app/logs/worker.log
truncate -s 750M app/logs/debug-dump.log
touch -d '2026-09-30' app/logs/archive/app-2026-09-{26..30}.log.gz
touch -d '2026-10-20' app/logs/archive/app-2026-10-{16..20}.log.gz
printf 'console.log("v1.4.0")\n' > app/releases/v1.4.0/server.js
printf 'console.log("v1.5.0")\n' > app/releases/v1.5.0/server.js
printf '#!/usr/bin/env bash\necho deploying\n' > app/releases/v1.5.0/deploy.sh
chmod 755 app/releases/v1.5.0/deploy.sh
truncate -s 120M app/releases/v1.4.0/bundle.tar.gz
ln -s releases/v1.5.0 app/current
touch -d '3 days ago' app/cache/session-{a,b,c}.tmp
touch app/cache/session-d.tmp
touch app/node_modules/left-pad/index.js app/.git/HEAD
truncate -s 3M 'app/uploads/Q3 reports/summary.pdf'
printf 'region,total\nnorth,1200\n' > 'app/uploads/Q3 reports/raw data.csv'
touch "app/uploads/invoice's copy.pdf" app/README.md app/readme.txt
printf 'port: 8080\n' > app/config.yml
printf 'DB_PASSWORD=hunter2\n' > app/.env
chmod 666 app/.env
tree -a app
du -sh appapp
├── .env
├── .git
│ └── HEAD
├── README.md
├── cache
│ ├── session-a.tmp
│ ├── session-b.tmp
│ ├── session-c.tmp
│ └── session-d.tmp
├── config.yml
├── current -> releases/v1.5.0
├── logs
│ ├── app.log
│ ├── app.log.1
│ ├── archive
│ │ ├── app-2026-09-26.log.gz
│ │ ├── app-2026-09-27.log.gz
│ │ ├── app-2026-09-28.log.gz
│ │ ├── app-2026-09-29.log.gz
│ │ ├── app-2026-09-30.log.gz
│ │ ├── app-2026-10-16.log.gz
│ │ ├── app-2026-10-17.log.gz
│ │ ├── app-2026-10-18.log.gz
│ │ ├── app-2026-10-19.log.gz
│ │ └── app-2026-10-20.log.gz
│ ├── debug-dump.log
│ └── worker.log
├── node_modules
│ └── left-pad
│ └── index.js
├── readme.txt
├── releases
│ ├── v1.4.0
│ │ ├── bundle.tar.gz
│ │ └── server.js
│ └── v1.5.0
│ ├── deploy.sh
│ └── server.js
└── uploads
├── Q3 reports
│ ├── raw data.csv
│ └── summary.pdf
└── invoice's copy.pdf
13 directories, 31 files
80K appOver 870 MB of apparent file size, 80 KB of actual disk use. The awkward names (Q3 reports, invoice's copy.pdf) are deliberate: real upload directories contain spaces and quotes, and they break careless pipelines.
How find works
The shape of every find command is:
find [starting points] [expression]find walks every file and directory below each starting point and evaluates the expression for each one. With no expression it prints everything:
find app/releasesapp/releases
app/releases/v1.4.0
app/releases/v1.4.0/bundle.tar.gz
app/releases/v1.4.0/server.js
app/releases/v1.5.0
app/releases/v1.5.0/server.js
app/releases/v1.5.0/deploy.shThree things to notice:
- Each result starts with the starting point you gave. Start from
.and you get./v1.4.0/...; start from an absolute path and you get absolute paths. - The starting directory itself is included.
- The order is the order entries are stored in the directory, not alphabetical (
server.jscame beforedeploy.sh). If you need sorted output, pipe it throughsort, covered in Searching and Filtering Text.
The expression is made of tests (like -name and -size, which are true or false for each file), actions (like -print and -delete, which do something), and operators that combine them. If the expression contains no action, find adds -print for you.
Matching names: -name, -iname, -path
-name matches the file's base name (the part after the last /) against a glob pattern. Always quote the pattern, so it reaches find instead of being expanded by the shell; the wildcards article shows what goes wrong when you don't.
find app -name '*.log'
find app -name '*.LOG'
find app -iname 'readme*'app/logs/app.log
app/logs/debug-dump.log
app/logs/worker.log
app/README.md
app/readme.txt-name must match the whole name, so *.log does not match app.log.1 or the .log.gz archives. It is case-sensitive, so *.LOG matched nothing; -iname ignores case.
-path matches against the whole path as find prints it, including directory names. Note that * in -path happily matches /:
find app -path '*/archive/*2026-10-1*'app/logs/archive/app-2026-10-19.log.gz
app/logs/archive/app-2026-10-16.log.gz
app/logs/archive/app-2026-10-17.log.gz
app/logs/archive/app-2026-10-18.log.gzFile types: -type
-type f selects regular files, -type d directories, and -type l symbolic links. You'll use -type f in almost every command that acts on files, so that -delete or chmod never hits a directory by accident.
find app -type d
find app -type l -lsapp
app/logs
app/logs/archive
app/cache
app/.git
app/uploads
app/uploads/Q3 reports
app/releases
app/releases/v1.4.0
app/releases/v1.5.0
app/node_modules
app/node_modules/left-pad
56537 0 lrwxrwxrwx 1 sid sid 15 Nov 9 21:49 app/current -> releases/v1.5.0app/current is a link to a directory, but it isn't listed by -type d, because by default find looks at links themselves and does not follow them. That also means find app/current prints just the link. Add a trailing slash, or use find -L to follow links:
find app/current
find app/current/
find -L app/current -name '*.js'app/current
app/current/
app/current/server.js
app/current/deploy.sh
app/current/server.jsSize: -size
-size takes a number with a unit suffix and an optional sign: + means "more than", - means "less than", no sign means "exactly".
| Suffix | Unit |
|---|---|
c | bytes |
k | KiB (1024 bytes) |
M | MiB |
G | GiB |
| none | 512-byte blocks (avoid; it confuses everyone) |
find app -size +100M
find app -size +1M -size -200Mapp/logs/debug-dump.log
app/releases/v1.4.0/bundle.tar.gz
app/uploads/Q3 reports/summary.pdf
app/releases/v1.4.0/bundle.tar.gzTwo tests in a row must both be true, so the second command is a range: more than 1 MiB and less than 200 MiB.
The rounding trap in -size -1M
find rounds each file's size up to whole units before comparing. A 33-byte file is "1 M" as far as -size is concerned, and 1 is not less than 1. So -size -1M only matches files of size zero:
find app -size -1Mapp/logs/worker.log
app/logs/archive/app-2026-09-27.log.gz
app/logs/archive/app-2026-10-19.log.gz
app/logs/archive/app-2026-10-16.log.gz
app/logs/archive/app-2026-10-17.log.gz
app/logs/archive/app-2026-09-30.log.gz
app/logs/archive/app-2026-09-26.log.gz
app/logs/archive/app-2026-09-28.log.gz
app/logs/archive/app-2026-09-29.log.gz
app/logs/archive/app-2026-10-18.log.gz
app/logs/archive/app-2026-10-20.log.gz
app/README.md
app/cache/session-d.tmp
app/cache/session-c.tmp
app/cache/session-b.tmp
app/cache/session-a.tmp
app/.git/HEAD
app/uploads/invoice's copy.pdf
app/readme.txt
app/node_modules/left-pad/index.jsapp/logs/app.log (33 bytes) and config.yml are missing, even though they are obviously smaller than a megabyte. For "smaller than 1 MiB", use a smaller unit: -size -1024k, or bytes with -size -1048576c. For "empty", say so directly with -empty, which also works on directories:
find app -type f -emptyThe output is the same list as -size -1M above, which tells you everything that matched was empty.
Time: -mtime, -mmin, -newer
Every file has a modification time (mtime): when its content last changed. -mtime n compares it in units of 24 hours, -mmin n in minutes. As with size, + means "older than" and - means "newer than".
date +%F
find app -type f -mtime +30
find app/cache -mmin -602026-11-09
app/logs/archive/app-2026-09-27.log.gz
app/logs/archive/app-2026-09-30.log.gz
app/logs/archive/app-2026-09-26.log.gz
app/logs/archive/app-2026-09-28.log.gz
app/logs/archive/app-2026-09-29.log.gz
app/cache
app/cache/session-d.tmpThe September archives are more than 30 days old; the October ones (20 days) are not. The second command also printed app/cache itself, because creating session-d.tmp updated the directory's modification time. Add -type f when you only want files.
-mtime has the same rounding as -size: the age is divided by 24 hours and the fraction is dropped. A file that is 47 hours old counts as "1 day", and -mtime +1 means "more than 1", so it does not match. In practice, -mtime +1 finds files at least 2 days old. The 3-day-old session files match both:
find app/cache -mtime +1
find app/cache -mtime +2app/cache/session-c.tmp
app/cache/session-b.tmp
app/cache/session-a.tmp
app/cache/session-c.tmp
app/cache/session-b.tmp
app/cache/session-a.tmpWhen you care about exact dates rather than ages, -newermt takes a date string, and -newer file compares against another file's mtime. The second form is the classic "what changed since the last deploy?" check:
find app/logs/archive -newermt '2026-10-01'
touch app/.last-deploy
printf 'debug: true\n' >> app/config.yml
find app -newer app/.last-deployapp/logs/archive
app/logs/archive/app-2026-10-19.log.gz
app/logs/archive/app-2026-10-16.log.gz
app/logs/archive/app-2026-10-17.log.gz
app/logs/archive/app-2026-10-18.log.gz
app/logs/archive/app-2026-10-20.log.gz
app/config.yml-printf lets you print any file attribute next to the name. %TY-%Tm-%Td %TH:%TM is the modification time, %p the path and %s the size in bytes:
find app/cache -type f -printf '%TY-%Tm-%Td %TH:%TM %p\n'
find app -size +1M -printf '%s bytes %p\n'2026-11-09 21:49 app/cache/session-d.tmp
2026-11-06 21:49 app/cache/session-c.tmp
2026-11-06 21:49 app/cache/session-b.tmp
2026-11-06 21:49 app/cache/session-a.tmp
786432000 bytes app/logs/debug-dump.log
3145728 bytes app/uploads/Q3 reports/summary.pdf
125829120 bytes app/releases/v1.4.0/bundle.tar.gzPermissions: -perm
-perm has three forms, and mixing them up is a common source of empty results. The modes are the same octal or symbolic modes that chmod uses, explained in File Permissions and Ownership.
| Form | Matches when… | Example |
|---|---|---|
-perm 644 | the mode is exactly 644 | -perm 666 |
-perm -mode | all of these bits are set (others may be too) | -perm -u+x |
-perm /mode | any of these bits is set | -perm /111 |
find app -type f -perm 666
find app -type f -perm -o+w
find app -type f -perm /111app/.env
app/.env
app/releases/v1.5.0/deploy.shThe .env file holding a database password is world-writable, which is exactly the kind of thing a security audit looks for. -perm /111 ("any execute bit") is the usual way to find executables.
-user name and -group name select by owner, and -perm and -user together answer questions like "which files in this web root are writable by someone other than the deploy user". The permissions article uses -perm -4000 to list setuid programs, a standard security-audit check.
Limiting depth: -maxdepth and -mindepth
-maxdepth 1 stops find from descending past the starting directory's direct children, which makes it a recursive-capable ls:
find app -maxdepth 1
find app -mindepth 2 -maxdepth 2 -type dapp
app/current
app/logs
app/README.md
app/cache
app/.git
app/uploads
app/releases
app/config.yml
app/.env
app/readme.txt
app/node_modules
app/logs/archive
app/uploads/Q3 reports
app/releases/v1.4.0
app/releases/v1.5.0
app/node_modules/left-padPut -maxdepth and -mindepth right after the starting points. They are global options that apply to the whole search no matter where they appear, and GNU find complains when they come after a test. It only prints such warnings when its input is a terminal, so I forced them on with -warn for this run:
find app -warn -type d -maxdepth 1find: warning: you have specified the global option -maxdepth after the argument -type, but global options are not positional, i.e., -maxdepth affects tests specified before it as well as those specified after it. Please specify global options before other arguments.
app
app/logs
app/cache
app/.git
app/uploads
app/releases
app/node_modulesCombining tests: AND, OR, NOT and parentheses
Tests written one after another are joined with an implicit AND (-a). -o is OR, and ! or -not is NOT:
find app/cache -type f ! -name 'session-d*'app/cache/session-c.tmp
app/cache/session-b.tmp
app/cache/session-a.tmpThe catch is precedence: AND binds tighter than OR, just like multiplication and addition. That matters as soon as you add an action:
find app/logs -name '*.log' -o -name '*.log.1'
find app/logs -name '*.log' -o -name '*.log.1' -print
find app/logs \( -name '*.log' -o -name '*.log.1' \) -printapp/logs/app.log
app/logs/app.log.1
app/logs/debug-dump.log
app/logs/worker.log
app/logs/app.log.1
app/logs/app.log
app/logs/app.log.1
app/logs/debug-dump.log
app/logs/worker.logThe first command worked because find wrapped the whole expression in an implicit -print. In the second, the explicit -print is ANDed with only the right-hand side, so it reads as "*.log, OR (*.log.1 AND print)", and the .log files matched but were never printed. Parentheses fix it. They must be escaped (\( and \)) or quoted, because they are special to the shell, and they need spaces around them.
The same mistake with -delete instead of -print deletes a different set of files than you meant. Whenever you use -o, use parentheses.
Skipping directories: -prune
Searching a project for .js files usually means not searching node_modules or .git:
find app -name '*.js'
find app \( -name node_modules -o -name .git \) -prune -o -name '*.js' -printapp/releases/v1.4.0/server.js
app/releases/v1.5.0/server.js
app/node_modules/left-pad/index.js
app/releases/v1.4.0/server.js
app/releases/v1.5.0/server.jsRead it as two branches joined by -o. Left branch: if the name is node_modules or .git, -prune (don't descend into it). Right branch: otherwise, if it's a .js file, print it. -prune doesn't just hide the directory from the output; find never reads it, which on a real project with 50,000 files in node_modules is the difference between instant and slow.
The explicit -print at the end is required. Leave it out and the implicit -print covers the whole expression, so the pruned directories themselves are printed:
find app \( -name node_modules -o -name .git \) -prune -o -name '*.js'app/.git
app/releases/v1.4.0/server.js
app/releases/v1.5.0/server.js
app/node_modulesActing on results
-print, -ls, -printf
You've seen -print (the default) and -printf. -ls prints an ls -l-style line with the inode number and block count in front:
find app/releases -name '*.js' -ls 56981 4 -rw-r--r-- 1 sid sid 22 Nov 9 21:49 app/releases/v1.4.0/server.js
56982 4 -rw-r--r-- 1 sid sid 22 Nov 9 21:49 app/releases/v1.5.0/server.js-exec ... {} \; versus -exec ... {} +
-exec runs a command on the results. {} is replaced by the file name, and the command is terminated in one of two ways:
\;runs the command once per file.+runs it with as many files as fit on one command line, likexargs.
find app/releases -name '*.js' -exec wc -c {} \;
find app/releases -name '*.js' -exec wc -c {} +22 app/releases/v1.4.0/server.js
22 app/releases/v1.5.0/server.js
22 app/releases/v1.4.0/server.js
22 app/releases/v1.5.0/server.js
44 totalThe total line only appears with +, because wc received both files in one run. A small helper shows the number of invocations directly (sh -c runs a tiny script, and $# is its argument count):
find app -type f -name '*.tmp' -exec sh -c 'echo "called with $# file(s)"' sh {} \;
find app -type f -name '*.tmp' -exec sh -c 'echo "called with $# file(s)"' sh {} +called with 1 file(s)
called with 1 file(s)
called with 1 file(s)
called with 1 file(s)
called with 4 file(s)With four files the difference is nothing. With 40,000, \; starts 40,000 processes and + starts a handful. Use + unless the command can only take one file at a time (for example mv old new).
-execdir works like -exec but runs the command from inside the directory containing each match, which is safer for commands that create files next to the original:
find app/releases -name 'server.js' -execdir pwd \;/home/sid/practice/find/app/releases/v1.4.0
/home/sid/practice/find/app/releases/v1.5.0-ok is -exec with a confirmation prompt for every file. It reads the answers from standard input; here I piped in y followed by three ns:
printf 'y\nn\nn\nn\n' | find app/cache -name '*.tmp' -ok rm {} \;
ls app/cache< rm ... app/cache/session-d.tmp > ? < rm ... app/cache/session-c.tmp > ? < rm ... app/cache/session-b.tmp > ? < rm ... app/cache/session-a.tmp > ? session-a.tmp session-b.tmp session-c.tmpAt a terminal you type the answers yourself, and each prompt waits on its own line.
-delete and the ordering trap
-delete removes each matched file (and empty directories). It is faster and safer than -exec rm because it handles any file name. But find evaluates the expression left to right for each file, and an action placed before a test runs before that test is checked. Let's prove it in a throwaway directory:
mkdir -p trap && touch trap/{keep.conf,old.tmp,notes.txt}
find trap -name '*.tmp' -print
find trap -delete -name '*.tmp'
ls -la traptrap/old.tmp
ls: cannot access 'trap': No such file or directoryThe preview with -print showed one file. The real command, with -delete first, deleted every file and the directory itself: -delete ran on each entry before -name was ever evaluated. Written in the right order, it does what the preview said:
mkdir -p trap && touch trap/{keep.conf,old.tmp,notes.txt}
find trap -name '*.tmp' -delete
ls trapkeep.conf
notes.txtPreview, then append -delete
Always run the command with -print first, read the list, then replace -print with -delete at the end of the same command line, without changing anything else. Never type -delete anywhere but last.
File names with spaces: -print0
Piping find into another command is common, and the default output, one name per line, breaks on names with spaces, quotes or newlines:
find app/uploads -name '*.csv' | xargs wc -l
find app/uploads -name '*.pdf' | xargs ls -lwc: app/uploads/Q3: No such file or directory
wc: reports/raw: No such file or directory
wc: data.csv: No such file or directory
0 total
xargs: unmatched single quote; by default quotes are special to xargs unless you use the -0 optionxargs split Q3 reports/raw data.csv into three words, and then refused to continue when it found the apostrophe in invoice's copy.pdf. The fix is to separate names with a null byte, the one character that can't appear in a file name. find -print0 writes names that way and xargs -0 reads them:
find app/uploads -name '*.csv' -print0 | xargs -0 wc -l
find app/uploads -name '*.pdf' -print0 | xargs -0 ls -l2 app/uploads/Q3 reports/raw data.csv
-rw-r--r-- 1 sid sid 3145728 Nov 9 21:49 app/uploads/Q3 reports/summary.pdf
-rw-r--r-- 1 sid sid 0 Nov 9 21:49 app/uploads/invoice's copy.pdfMake -print0 | xargs -0 a habit whenever file names travel through a pipe. (Pipes themselves are covered in Redirection and Pipes.)
xargs: turning input into arguments
xargs reads items from standard input and runs a command with those items as arguments. It isn't limited to find; it is the general tool for "run this command on every line of that list". By default it splits on any whitespace and packs as many items as possible into each command:
printf 'web01 web02\nweb03\n' | xargs echo ping
printf 'web01 web02\nweb03\n' | xargs -n 1 echo ping
printf 'web01 web02\nweb03\n' | xargs -n 2 echo pingping web01 web02 web03
ping web01
ping web02
ping web03
ping web01 web02
ping web03-n N limits each run to N items. -I {} runs the command once per input line and substitutes the line wherever {} appears, which you need when the item isn't the last argument:
printf '%s\n' web01 web02 web03 | xargs -I {} echo "ssh {} uptime"
find app/releases -name '*.js' -print0 | xargs -0 -I {} cp {} {}.bak
find app/releases -name '*.bak'ssh web01 uptime
ssh web02 uptime
ssh web03 uptime
app/releases/v1.4.0/server.js.bak
app/releases/v1.5.0/server.js.bakRunning in parallel with -P
-P N runs up to N commands at the same time. Here each command is sleep 1, so the timing shows the effect clearly (time reports how long the whole thing took):
time (printf '%s\n' 1 1 1 1 | xargs -n 1 sleep)
time (printf '%s\n' 1 1 1 1 | xargs -n 1 -P 4 sleep)
real 0m4.018s
user 0m0.011s
sys 0m0.001s
real 0m1.019s
user 0m0.003s
sys 0m0.031sFour seconds sequentially, one second in parallel. That is how you compress a directory of logs on all CPU cores (xargs -0 -n 1 -P 4 gzip), or check a list of servers concurrently. Parallel jobs write their output in whatever order they finish, so don't use -P when output order matters.
Empty input and -r
When the input is empty, GNU xargs still runs the command once, with no arguments:
find app -name '*.bak' -name '*.zzz' | xargs rm
find app -name '*.bak' -name '*.zzz' | xargs -r rm
echo "exit: $?"rm: missing operand
Try 'rm --help' for more information.
exit: 0-r (--no-run-if-empty) skips the run entirely. Add it to any xargs in a script where "nothing matched" is a normal outcome. find -exec ... + never has this problem, which is one reason to prefer it when you don't need xargs features like -P.
locate: searching a prebuilt index
find walks the disk every time. locate instead searches a database of file names built in advance by updatedb, usually from a daily system timer, so it answers in milliseconds even on huge filesystems. On current Ubuntu the implementation is a package called plocate, and it is not installed by default. On my test system:
locate nginx.confCommand 'locate' not found, but can be installed with:
sudo apt install plocateI didn't install it for this article, so the following is description rather than tested output. After sudo apt install plocate, the package builds its database, and locate nginx.conf prints every indexed path containing that string. locate -i ignores case, and sudo updatedb refreshes the index on demand. The trade-off is freshness: files created after the last updatedb run are missing, and deleted files may still be listed. Use locate for "where on this machine is the file called X?", and find for anything that depends on the current state, sizes, times or permissions, or that needs an action.
Finding commands: type, which, command -v
find and locate search for files. A different question is "what will run when I type this name?" The shell checks aliases, functions and builtins before it searches PATH (explained in Variables, Quoting, and the Environment), and only type knows about all of them:
type -a echo
which echo
which -a echo
command -v echoecho is a shell builtin
echo is /usr/bin/echo
echo is /bin/echo
/usr/bin/echo
/usr/bin/echo
/bin/echo
echoWhen you type echo, the builtin runs. which is a separate program that only searches PATH, so it reports /usr/bin/echo, which is not what Bash actually runs. That's why I recommend type at the prompt, and command -v in scripts:
command -v git
command -v kubectl
echo "exit: $?"
type -t ls cd if git
if command -v git >/dev/null; then echo "git is installed"; fi/usr/bin/git
exit: 1
file
builtin
keyword
file
git is installedcommand -v prints the path for programs (or the bare name for builtins) and fails with exit status 1 when the command doesn't exist, which makes it the standard dependency check at the top of a script. type -t prints just the kind of each name: alias, keyword, function, builtin or file. (Exit statuses and if are covered in Command Substitution, Chaining, and Exit Codes.)
Where you'll use this
Cleaning up old logs on a schedule
This is the most common find job in operations. Save it as clean-logs.sh:
#!/usr/bin/env bash
# clean-logs.sh - delete compressed logs older than KEEP_DAYS (default 30)
log_dir=${1:?usage: clean-logs.sh LOG_DIR}
days=${KEEP_DAYS:-30}
echo "Removing *.log.gz older than $days days from $log_dir"
find "$log_dir" -type f -name '*.log.gz' -mtime +"$days" -print -delete
echo "Archives left: $(find "$log_dir" -type f -name '*.log.gz' | wc -l)"Preview with -print first, then run it, then run it with a shorter retention:
find app/logs -type f -name '*.log.gz' -mtime +30 -print
bash clean-logs.sh app/logs
KEEP_DAYS=14 bash clean-logs.sh app/logsapp/logs/archive/app-2026-09-27.log.gz
app/logs/archive/app-2026-09-30.log.gz
app/logs/archive/app-2026-09-26.log.gz
app/logs/archive/app-2026-09-28.log.gz
app/logs/archive/app-2026-09-29.log.gz
Removing *.log.gz older than 30 days from app/logs
app/logs/archive/app-2026-09-27.log.gz
app/logs/archive/app-2026-09-30.log.gz
app/logs/archive/app-2026-09-26.log.gz
app/logs/archive/app-2026-09-28.log.gz
app/logs/archive/app-2026-09-29.log.gz
Archives left: 5
Removing *.log.gz older than 14 days from app/logs
app/logs/archive/app-2026-10-19.log.gz
app/logs/archive/app-2026-10-16.log.gz
app/logs/archive/app-2026-10-17.log.gz
app/logs/archive/app-2026-10-18.log.gz
app/logs/archive/app-2026-10-20.log.gz
Archives left: 0-print -delete logs each file as it's removed, so the cron job's output is an audit trail. -type f and the specific -name pattern ensure that nothing else in the directory can match. The ${1:?...} and ${KEEP_DAYS:-30} expansions come from the variables article, and scheduling it nightly is covered in System Monitoring and Scheduling with cron and systemd.
Finding what is filling the disk
-exec ls -lhS {} + hands every match to a single ls, which sorts by size and prints human-readable sizes. -xdev keeps find on one filesystem so it doesn't wander into other mounts:
find app -xdev -type f -size +1M -exec ls -lhS {} +-rw-r--r-- 1 sid sid 750M Nov 9 21:50 app/logs/debug-dump.log
-rw-r--r-- 1 sid sid 120M Nov 9 21:50 app/releases/v1.4.0/bundle.tar.gz
-rw-r--r-- 1 sid sid 3.0M Nov 9 21:50 app/uploads/Q3 reports/summary.pdfThe same command works on a whole system. On my test machine, searching /usr for anything over 50 MB, with permission errors discarded:
find /usr -xdev -type f -size +50M -exec ls -lhS {} + 2>/dev/null-rw-r--r-- 1 root root 137M Apr 21 2026 /usr/lib/x86_64-linux-gnu/libLLVM.so.20.1One caveat for sparse files like the practice ones: ls and find -size report the apparent size, while du reports the space actually used. When those disagree wildly, it's usually a sparse file (VM images, databases), and deleting it frees less than you'd expect.
Fixing permissions in bulk
A release directory where some files are too private and directories are inconsistent is a classic deployment problem. The standard fix is directories 755, files 644, scripts executable:
chmod 700 app/releases/v1.4.0
chmod 600 app/releases/v1.4.0/server.js
find app/releases -printf '%M %p\n'
find app/releases -type d -exec chmod 755 {} +
find app/releases -type f -exec chmod 644 {} +
find app/releases -type f -name '*.sh' -exec chmod 755 {} +
find app/releases -printf '%M %p\n'drwxr-xr-x app/releases
drwx------ app/releases/v1.4.0
-rw-r--r-- app/releases/v1.4.0/bundle.tar.gz
-rw------- app/releases/v1.4.0/server.js
drwxr-xr-x app/releases/v1.5.0
-rw-r--r-- app/releases/v1.5.0/server.js
-rwxr-xr-x app/releases/v1.5.0/deploy.sh
drwxr-xr-x app/releases
drwxr-xr-x app/releases/v1.4.0
-rw-r--r-- app/releases/v1.4.0/bundle.tar.gz
-rw-r--r-- app/releases/v1.4.0/server.js
drwxr-xr-x app/releases/v1.5.0
-rw-r--r-- app/releases/v1.5.0/server.js
-rwxr-xr-x app/releases/v1.5.0/deploy.sh%M in -printf is the permission string as ls -l shows it. Separating -type d from -type f is the point: chmod -R 644 would remove the execute bit from directories and make them impossible to enter. The permissions article explains why.
Common mistakes
Permission denied noise hiding the answer
Searching system directories as a normal user produces an error for every directory you can't read, and the real result is easy to miss:
find /etc -name 'ssh_config'/etc/ssh/ssh_config
find: ‘/etc/credstore’: Permission denied
find: ‘/etc/ssl/private’: Permission denied
find: ‘/etc/polkit-1/rules.d’: Permission denied
find: ‘/etc/credstore.encrypted’: Permission deniedThe errors go to standard error, so 2>/dev/null discards them and leaves only the results:
find /etc -name 'ssh_config' 2>/dev/null/etc/ssh/ssh_configOnly do this when you know the errors don't matter. In a cleanup script, a "Permission denied" may be the reason files aren't being deleted.
Other traps covered above
-deletebefore the tests deletes everything under the starting point. Put it last, after a-printpreview.-owithout parentheses applies your action to only one side of the OR.-size -1Mmatches only empty files because of rounding up. Use-size -1024kor-empty.find | xargswithout-print0/-0breaks on spaces and quotes in file names.- An unquoted
-name *.loggets expanded by the shell beforefindsees it. xargson empty input runs the command once with no arguments; add-r.
Summary
find PATH EXPRESSIONwalks the tree and evaluates tests (-name,-type,-size,-mtime,-perm...) left to right for each entry; output is in directory order, not sorted.- Quote patterns:
-name '*.log'.-namematches the base name and-inameignores case;-pathmatches the whole path. +nmeans more than,-nless than. Sizes and ages round up to whole units, so-size -1Mmeans empty and-mtime +1means at least 2 days old.-perm 644is exact,-perm -modeneeds all bits,-perm /modeneeds any bit.- Tests are ANDed;
-ois OR with lower precedence, so wrap OR groups in\( ... \).-prune -o ... -printskips directories likenode_moduleswithout reading them. -exec cmd {} +batches files into few runs;\;runs once per file.-deletegoes last, always after a-printpreview.- Use
-print0 | xargs -0for any file names in a pipe.xargs -n,-I {},-Pand-rcontrol batching, placement, parallelism and empty input. locatesearches a prebuilt index (fast, possibly stale, often not installed). To find commands, usetype -aat the prompt andcommand -vin scripts.
Exercises
Every exercise starts from a fresh practice directory: rm -rf ~/practice/find and run the setup block from the top of the article again.
List every file in app/cache that is more than a day old, printing its modification date in front of the path, like 2026-11-06 app/cache/session-a.tmp.
Show Solution
find app/cache -type f -mtime +1 -printf '%TY-%Tm-%Td %p\n'2026-11-06 app/cache/session-c.tmp
2026-11-06 app/cache/session-b.tmp
2026-11-06 app/cache/session-a.tmpYour dates will be three days before the day you ran the setup. -mtime +1 matches files at least two full days old, which the three older session files are and session-d.tmp isn't. -type f keeps the app/cache directory itself out of the list.
You find a script that calls echo -e, and someone says "it uses /usr/bin/echo, because that's what which echo says". Show every echo the shell could run, in order, and explain which one actually runs.
Show Solution
type -a echo
which echoecho is a shell builtin
echo is /usr/bin/echo
echo is /bin/echo
/usr/bin/echoThe builtin comes first, so Bash runs the builtin echo. which only searches PATH and knows nothing about builtins, aliases or functions, so its answer is misleading here. That's why type (interactive) and command -v (scripts) are the reliable tools.
List every .js file under app, skipping node_modules and .git entirely, with each file's size in bytes before its path, separated by a tab.
Hint
Combine -prune with -printf instead of -print. In -printf, %s is the size and \t is a tab.
Show Solution
find app \( -name node_modules -o -name .git \) -prune -o -type f -name '*.js' -printf '%s\t%p\n'22 app/releases/v1.4.0/server.js
22 app/releases/v1.5.0/server.js-printf is an action, so it plays the same role as the explicit -print: it only applies to the right-hand branch, and the pruned directories aren't printed.
Copy every .pdf and .csv file from anywhere under app/uploads into a new directory backup/, in one pipeline that copes with spaces and apostrophes. Then list backup.
Hint
You need parentheses for the OR, -print0, xargs -0, and cp -t DIR, which takes the destination first so the files can come last.
Show Solution
mkdir -p backup
find app/uploads -type f \( -name '*.pdf' -o -name '*.csv' \) -print0 | xargs -0 cp -t backup/
ls -l backuptotal 4
-rw-r--r-- 1 sid sid 0 Nov 9 21:50 invoice's copy.pdf
-rw-r--r-- 1 sid sid 24 Nov 9 21:50 raw data.csv
-rw-r--r-- 1 sid sid 3145728 Nov 9 21:50 summary.pdfcp -t backup/ puts the target directory first, so xargs can append any number of source files after it. Without -print0/-0, xargs would have stopped at the apostrophe with "unmatched single quote".
Compress, with gzip, every log file directly in app/logs (not in archive/) whose name ends in .log or in .log. followed by one digit, except debug-dump.log, and except empty files. Run two gzip processes in parallel. Preview the list first.
Show Solution
find app/logs -maxdepth 1 -type f \( -name '*.log' -o -name '*.log.[0-9]' \) ! -name 'debug-*' ! -empty -print
find app/logs -maxdepth 1 -type f \( -name '*.log' -o -name '*.log.[0-9]' \) ! -name 'debug-*' ! -empty -print0 | xargs -0 -n 1 -P 2 gzip
ls app/logsapp/logs/app.log
app/logs/app.log.1
app.log.1.gz app.log.gz archive debug-dump.log worker.log-maxdepth 1 keeps find out of archive/, the parenthesised OR covers both name shapes, and the two negations drop the debug dump and the empty worker.log. -n 1 -P 2 gives each gzip one file and runs two at a time. Since gzip replaces each file with a .gz version, the preview step is what tells you exactly what is about to change.
Tested with: GNU Bash 5.2.21 on Ubuntu 24.04 (WSL2), November 2026, with GNU findutils 4.9.0 (find, xargs). Every command was run as shown against the practice directory, rebuilt fresh for each batch of examples, so modification times show 21:49 in some outputs and 21:50 in others. The large files are sparse, created with truncate, so the practice tree uses about 80 KB of disk. locate/plocate was not installed on the test system and I did not install it, so the locate options are described, not demonstrated.
Written by The Dark Debugger
Engineer documenting the things that took me too long to learn, so they take you less time. Every Bash tutorial here is tested end to end before publishing.