How I Use Find and Xargs to Delete Temp Files Older Than 7 Days Without Risking rm ‑rf

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 – find lets you restrict the search to a specific path, depth, file type, age, size, or owner.
  • Safety – -delete removes only the matched files; it never walks into a directory you didn’t ask for.
  • Speed – xargs batches deletions, reducing the number of rm invocations.
  • Robustness – -print0 + xargs -0 handles 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 f skips directories and symlinks.
  • -mtime +7 matches files whose modification time is more than seven days ago.
  • -print0 outputs a null‑terminated list; xargs -0 consumes it safely.
  • -v gives you a quick audit trail.

If you prefer a single‑step solution and your find supports it, replace the pipe with -delete:

[Read More]