Cleaning up old temp files is a daily chore that can quickly become dangerous if you use the wrong tool.
A single misplaced rm -rf can wipe out a whole directory tree, and that risk grows when you’re running scripts as root.
The combination of find and xargs (or -delete) gives you a precise, race‑condition‑aware way to target only the files you really want gone.
Why find + xargs beats a blind rm -rf
- Scope control –
findlets you restrict the search to a specific path, depth, file type, age, size, or owner. - Safety –
-deleteremoves only the matched files; it never walks into a directory you didn’t ask for. - Speed –
xargsbatches deletions, reducing the number ofrminvocations. - Robustness –
-print0+xargs -0handles filenames with spaces, newlines, or other odd characters.
A minimal, production‑ready command
# Delete regular files in /tmp older than 7 days
find /tmp -type f -mtime +7 -print0 | xargs -0 rm -v
-type fskips directories and symlinks.-mtime +7matches files whose modification time is more than seven days ago.-print0outputs a null‑terminated list;xargs -0consumes it safely.-vgives you a quick audit trail.
If you prefer a single‑step solution and your find supports it, replace the pipe with -delete:
find /tmp -type f -mtime +7 -delete
-delete is atomic for each file, so there’s no window where a file could be moved between the find and delete stages.
Dry‑run before you kill
find /tmp -type f -mtime +7 -ls
-ls lists the candidates with timestamps and permissions.
Once you’re satisfied, switch to -delete or the xargs pipeline.
Performance vs. safety
-deleteis usually faster because it avoids spawningrm.xargsshines when you’re deleting thousands of files; it batches the calls and keeps the kernel from being flooded withrmprocesses.- If you need to preserve the directory structure (e.g., you’re cleaning a nested cache), add
-mindepth 1 -maxdepth 1to limit recursion.
When systemd‑tmpfiles is a better fit
For regular, automated cleanup of standard temp directories, systemd-tmpfiles is the canonical tool.
See the official docs: https://systemd.io/TMPFILES/ and the source: https://github.com/systemd/systemd.
Security checklist
- Run as the least‑privileged user that owns the files.
- Avoid
sudounless necessary; if you must, double‑check the command. - Use
-useror-groupto limit the scope to a specific account. - Log the output (
teeor redirect to a log file) so you can audit what was removed. - Test in a staging environment before deploying to production.
See also
- When Wayland Won’t Run My Games: Tweaking a Laptop for Better Battery Life
- When a backup script keeps my CPU pegged: a quick ps, nice, ionice tweak to keep the terminal responsive.
- Why my headphone jack stopped working after the latest update—and how a single udev rule brought it back
- How I Configured Caddy as a Reverse Proxy for My Home Lab and Solved the HTTPS Redirect Bug
- How I Prevented a Rootless Podman Container From Filling My Disk With Logs