Cleaning Up
With my desktop machine's last system upgrade, I changed how I managed my /tmp directory. Before the upgrade, my configuration mounted a tmpfs on /tmp at startup, but now, it mounts a separate ext2 partition for /tmp. Linux implements the tmpfs filesystemtype in swap, making the contents of the directory really temporary; files and directories in such a filesystem vanish on reboot. But, now with the ext2 filesystem, /tmp files and directories stick around. This means that I now needed something to clean up my /tmp directory on a regular basis. So, I wrote a short script to do just that.
The script is just a series of find(1) commands that search a configuration-selected set of temporary directories and delete policy-selected files, symlinks, sockets, and directories. It is not a complex script, and, as such, is easy enough to modify for new circumstances.
- The script (called /usr/local/sbin/cleantmp.sh) looks like:
-
#!/bin/bash # cleantmp.sh - Remove unused files from tmp directories # ------------- Default Configuration -------------------- # TMP_DIRS - List of directories to search # FILE_AGE - # days ago (rounded up) that file was last accessed # LINK_AGE - # days ago (rounded up) that symlink was last accessed # SOCK_AGE - # days ago (rounded up) that socket was last accessed TMP_DIRS="/tmp /var/tmp /usr/src/tmp /mnt/tmp" FILE_AGE=+1 LINK_AGE=+1 SOCK_AGE=+1 #----------------------------------------------------------------- cd / /usr/bin/logger "cleantmp.sh[$$] - Begin cleaning tmp directories" # delete any tmp files that are more than 2 days old /usr/bin/find $TMP_DIRS \ -depth \ -type f -a -ctime $FILE_AGE \ -print -delete # delete any old tmp symlinks /usr/bin/find $TMP_DIRS \ -depth \ -type l -a -ctime $LINK_AGE \ -print -delete # delete any empty files /usr/bin/find $TMP_DIRS \ -depth \ -type f -a -empty \ -print -delete # Delete any old Unix sockets /usr/bin/find $TMP_DIRS \ -depth \ -type s -a -ctime $SOCK_AGE -a -size 0 \ -print -delete # delete any empty directories (other than lost+found) /usr/bin/find $TMP_DIRS \ -depth -mindepth 1 \ -type d -a -empty -a ! -name 'lost+found' \ -print -delete /usr/bin/logger "cleantmp.sh[$$] - Done cleaning tmp directories" exit 0
In /etc/cron.hourly, I have a symlink to this cleantmp.sh script, so that, hour-by-hour, the script will keep my temporary file directories clean and neat. Now, I know that my /tmp directory won't take up space with unnecessary files and directories, and all with just a little scrpiting knowledge.
| Attachment | Size |
|---|---|
| cleantmp.sh | 1.91 KB |