Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

One of my server daemons uses a lot of space in /tmp. Because I don't want to reboot my machine when the server runs out of disk space, I need to run a CRON script that removes old temporary files.

What would be good a way to recursively remove all files and directories under /tmp which are more than 1 hour old from user , say www-data? Of course it should not resolve symlinks and start removing files elsewhere on the system. I am using Ubuntu 12.04 and will run this cronjob as root.

share|improve this question
up vote 5 down vote accepted

Drop a script like this into /etc/cron.hourly:

find /tmp -mmin +60 -user www-data -delete

You may want to first manually run the find without the -delete option to check your work.

Hmm, also, to kill the subdirectories (since -delete only removes files), add in another line:

find /tmp -mmin +60 -user www-data -type d -empty -exec rmdir {} \;

Depending on subdirectory depth, the second find may take a little while to work its way back up, as mtime for the parent directory will be updated as the subdirectory is removed.

share|improve this answer
It should be -mmin +60 – Mircea Vutcovici Apr 24 '12 at 18:54
@MirceaVutcovici D'oh. Thanks. Updating the Answer now. – cjc Apr 24 '12 at 18:55
What about the cleanup of the empty subdirectories once the files have been cleared? – mdpc Apr 24 '12 at 18:58
Updated with a directory killing line. – cjc Apr 24 '12 at 19:04
You will need to DROP the mmin +60 with the directories since deleting files below it will change the modification date/time. – mdpc Apr 24 '12 at 19:26

You can also check with the command lsof if the temp file is opened before delete it.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.