3

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.

2 Answers 2

7

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.

8
  • It should be -mmin +60 Apr 24, 2012 at 18:54
  • @MirceaVutcovici D'oh. Thanks. Updating the Answer now.
    – cjc
    Apr 24, 2012 at 18:55
  • What about the cleanup of the empty subdirectories once the files have been cleared?
    – mdpc
    Apr 24, 2012 at 18:58
  • Updated with a directory killing line.
    – cjc
    Apr 24, 2012 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, 2012 at 19:26
0

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .