Linux – script to remove all files in /tmp from a certain user

bashcronlinuxUbuntu

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.

Best Answer

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.