如何實現(xiàn)Linux tmp目錄自動清理
在Linux系統(tǒng)中/tmp文件夾下的文件是會被清理、刪除的,文件清理的規(guī)則是如何設(shè)定的呢? 以Redhat為例,這個主要是因為作業(yè)里面會調(diào)用tmpwatch命令刪除那些一段時間沒有訪問的文件。
那么什么是tmpwatch呢?其實tmpwatch是一個命令或者說是一個包。如下所示
- tmpwatch - removes files which haven’t been accessed for a period of time
- [root@DB-Server ~]# rpm -qa | grep tmpwatch
- tmpwatch-2.9.7-1.1.el5.5
- [root@DB-Server ~]# whereis tmpwatch
- tmpwatch: /usr/sbin/tmpwatch /usr/share/man/man8/tmpwatch.8.gz
- [root@DB-Server ~]# file /usr/sbin/tmpwatch
- /usr/sbin/tmpwatch: ELF 64-bit LSB executable, AMD x86-64, version 1 (SYSV), for GNU/Linux 2.6.9, dynamically linked (uses shared libs), for GNU/Linux 2.6.9, stripped
- [root@DB-Server ~]#
關(guān)于tmpwatch命令的參數(shù),不同版本可能有所不同,下面以Red Hat Enterprise Linux Server release 5.7下TMPWATCH(8)為列
作用:
刪除一段時間沒有被訪問的文件。
參數(shù):
-u 按照文件的***access時間,即***訪問時間為參考。默認(rèn)選項。可通過ls -lu查看。
-m 按照文件的***modified時間,即***修改時間為參考。可通過ls -l查看。
-c 按照文件的-ctime時間做參考,ctime更新的條件為寫入、更改屬主、權(quán)限??赏ㄟ^ls -lc查看。
-M 按照目錄的修改時間來刪除目錄而不是訪問時間。
-a 刪除所有類型文件。包括目錄和symbolic links
-d --nodirs 排除目錄文件,即使是空目錄。
-d --nosysmlinks 排除symbolic links類型文件。
-f 強制刪除那些root沒有寫權(quán)限的文件。比如root的readonly文件
-q 只報告錯誤信息。
-x /PATH 排除特定目錄,即不刪除該子目錄里的文件。
-U user_name 排除屬于特定用戶的文件,即不刪除該用戶的文件。
-v 顯示刪除過程。默認(rèn)是不顯示刪除了什么文件,直接刪除的。
-t 用于測試,并不真正刪除文件,能顯示出要刪除文件的過程。
-d 不刪除文件里的子目錄,但是子目錄里面的文件還是會被刪除。
參數(shù)后加時間,默認(rèn)是hours。也可以使用30d表示30天,但是有些版本只支持hours。 時間后是要檢查的目錄。可以多個目錄用空格分開。如下所示表示720小小時~=30天。
- [root@DB-Server ~]# more /etc/cron.daily/tmpwatch
- flags=-umc
- /usr/sbin/tmpwatch "$flags" -x /tmp/.X11-unix -x /tmp/.XIM-unix \
- -x /tmp/.font-unix -x /tmp/.ICE-unix -x /tmp/.Test-unix \
- -X '/tmp/hsperfdata_*' 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"
- fi
- done
- [root@DB-Server ~]#
如果你想將強制刪除30天沒有訪問的文件改為7天,只需"/usr/sbin/tmpwatch "$flags" 720 /var/tmp"和"/usr/sbin/tmpwatch "$flags" -f 720 "$d" 里面的720改為189即可。