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:

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

  • -delete is usually faster because it avoids spawning rm.
  • xargs shines when you’re deleting thousands of files; it batches the calls and keeps the kernel from being flooded with rm processes.
  • If you need to preserve the directory structure (e.g., you’re cleaning a nested cache), add -mindepth 1 -maxdepth 1 to 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

  1. Run as the least‑privileged user that owns the files.
  2. Avoid sudo unless necessary; if you must, double‑check the command.
  3. Use -user or -group to limit the scope to a specific account.
  4. Log the output (tee or redirect to a log file) so you can audit what was removed.
  5. Test in a staging environment before deploying to production.

See also