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: