clean linux tmp
Doing some security check on my laptop I found that some files are kept on disk even I do not want to – /tmp directory
. Temp is kind of places in system that should not be kept on encrypted partition, so I have decided to use tmpfs
. First define an /etc/fstab
entry to keep /tmp
on tmpfs
:
tmpfs /tmp tmpfs rw,noexec,noatime,mode=1777 0 0 tmpfs /var/tmp tmpfs rw,noexec,noatime,mode=1777 0 0
Clean all data and mount it:
rm -rf /tmp/* /var/tmp/* mount /tmp mount /var/tmp
Now your data is kept only till yours computer is restarted. But wait it keeps growing, I restart my laptop once few months, what then? No problem a handy script might be useful, save it as /root/bin/clean_tmp.sh
:
#!/bin/bash : old_minutes:${old_minutes:=60} list_used() { lsof +D "$1" 2>/dev/null | awk 'NR>1{print $9}' } list_old() { find "$1" -type f -amin +$old_minutes 2>/dev/null } list_unused_old() { diff <(list_used "$1") <(list_old "$1") | awk '$1==">"{print $2}' } list_empty_dirs() { find "$1" -type d -empty } clean_all() { typeset _tmp_dir for _tmp_dir in "$@" do list_unused_old "${_tmp_dir}" | xargs rm -fv list_empty_dirs "${_tmp_dir}" | xargs rm -fvr done } clean_all /tmp /var/tmp
What it does? – remove all files older then 60 minutes and not used by any application. Now connect script in root cron (sudo crontab -e
):
5 * * * * /root/bin/clean_tmp.sh
Now your temp is secure and clean. You will get list of removed files on your local mail account, to prevent this email remove just v
from xargs rm -fv
from the script.