Using tmpwatch to automate temporary file cleanup on Linux hosts

I have seen a number of applications that use temporary working directories, and over time files get orphaned in these directories. Typically when this happens I need to fire up find to locate old files, and then use the exec flag to remove them once I know they are no longer needed. In some cases I don’t need to check whether these files need to be kept, and I can just blast old cruft that was created. For these situations, I have come to rely on the tmpwatch utility that ships with CentOS Linux. Tmpwatch can be configured to remove files older than X hours, and has a daily cron job that kicks off from /etc/cron.daily to purge a select few files in /tmp and /var/:

$ cat /etc/cron.daily/tmpwatch

/usr/sbin/tmpwatch "$flags" -x /tmp/.X11-unix -x /tmp/.XIM-unix \
-x /tmp/.font-unix -x /tmp/.ICE-unix -x /tmp/.Test-unix 240 /tmp

/usr/sbin/tmpwatch "$flags" 720 /var/tmp

for d in /var/{cache/man,catman}/{cat?,X11R6/cat?,local/cat?}; do
    if [ -d "$d" ]; then
        /usr/sbin/tmpwatch "$flags" -f 720 "$d"

To clean up temporary files in the directory named /opt/APP/tmp that are over 90-hours old, a tmpwatch entry similar to the following can be created:

$ /usr/sbin/tmpwatch -umc 90 /opt/APP/tmp

If you are curious what tmpwatch will do, you can run it in test mode by adding the “-t” (operate in test mode) and “-v” (verbose output) options to the command line. This is a useful utility, and has a bunch of cool options to control what is and isn’t removed (I need to test out the “-s” (check for open files before deleting them) option in the future).

This article was posted by Matty on 2009-05-01 11:01:00 -0400 -0400