Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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

2 Answers 2

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

 
discard

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.