如何實(shí)現(xiàn)Linux tmp目錄自動(dòng)清理
在Linux系統(tǒng)中/tmp文件夾下的文件是會(huì)被清理、刪除的,文件清理的規(guī)則是如何設(shè)定的呢? 以Redhat為例,這個(gè)主要是因?yàn)樽鳂I(yè)里面會(huì)調(diào)用tmpwatch命令刪除那些一段時(shí)間沒(méi)有訪問(wèn)的文件。
那么什么是tmpwatch呢?其實(shí)tmpwatch是一個(gè)命令或者說(shuō)是一個(gè)包。如下所示
- 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í)間沒(méi)有被訪問(wèn)的文件。
參數(shù):
-u 按照文件的***access時(shí)間,即***訪問(wèn)時(shí)間為參考。默認(rèn)選項(xiàng)。可通過(guò)ls -lu查看。
-m 按照文件的***modified時(shí)間,即***修改時(shí)間為參考。可通過(guò)ls -l查看。
-c 按照文件的-ctime時(shí)間做參考,ctime更新的條件為寫入、更改屬主、權(quán)限。可通過(guò)ls -lc查看。
-M 按照目錄的修改時(shí)間來(lái)刪除目錄而不是訪問(wèn)時(shí)間。
-a 刪除所有類型文件。包括目錄和symbolic links
-d --nodirs 排除目錄文件,即使是空目錄。
-d --nosysmlinks 排除symbolic links類型文件。
-f 強(qiáng)制刪除那些root沒(méi)有寫權(quán)限的文件。比如root的readonly文件
-q 只報(bào)告錯(cuò)誤信息。
-x /PATH 排除特定目錄,即不刪除該子目錄里的文件。
-U user_name 排除屬于特定用戶的文件,即不刪除該用戶的文件。
-v 顯示刪除過(guò)程。默認(rèn)是不顯示刪除了什么文件,直接刪除的。
-t 用于測(cè)試,并不真正刪除文件,能顯示出要?jiǎng)h除文件的過(guò)程。
-d 不刪除文件里的子目錄,但是子目錄里面的文件還是會(huì)被刪除。
參數(shù)后加時(shí)間,默認(rèn)是hours。也可以使用30d表示30天,但是有些版本只支持hours。 時(shí)間后是要檢查的目錄。可以多個(gè)目錄用空格分開。如下所示表示720小小時(shí)~=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 ~]#
如果你想將強(qiáng)制刪除30天沒(méi)有訪問(wèn)的文件改為7天,只需"/usr/sbin/tmpwatch "$flags" 720 /var/tmp"和"/usr/sbin/tmpwatch "$flags" -f 720 "$d" 里面的720改為189即可。