2008-10-30 68 views
144

我在寫一個需要刪除舊文件的bash腳本。如何刪除超過X小時的文件

它使用當前實現:

find $LOCATION -name $REQUIRED_FILES -type f -mtime +1 -delete 

這將刪除超過1天的年齡較大的文件。

但是,如果我需要更高分辨率的一天,比如說6個小時的時間呢?有沒有一個很好的乾淨的方式來做到這一點,就像使用find和-mtime一樣?

回答

222

您的find是否有-mmin選項?這可以讓你測試自去年修改分鐘的數量:

find $LOCATION -name $REQUIRED_FILES -type f -mmin +360 -delete 

或者,也許看看使用tmpwatch做同樣的工作。 phjr也在評論中推薦tmpreaper

+5

感謝大家的回答,-mmin正是我需要的:)不知何故,我錯過了它的手冊頁。 – 2008-10-30 08:43:45

+2

我沒有-mmin :( – xtofl 2008-10-30 08:45:57

+1

tmpwatch是給你的然後 – 2008-10-30 08:48:47

2

-mmin是分鐘。

嘗試查看手冊頁。

man find 

更多類型。

7

你可以這樣做:在1小時前創建一個文件,並使用-newer file參數。

(或使用touch -t創建這樣的文件)。

1

在SunOS 5.10

Example 6 Selecting a File Using 24-hour Mode 


The descriptions of -atime, -ctime, and -mtime use the ter- 
minology n ``24-hour periods''. For example, a file accessed 
at 23:59 is selected by: 


    example% find . -atime -1 -print 




at 00:01 the next day (less than 24 hours later, not more 
than one day ago). The midnight boundary between days has no 
effect on the 24-hour calculation. 
0

find $PATH -name $log_prefix"*"$log_ext -mmin +$num_mins -exec rm -f {} \;

0

這裏是一個可以在@iconoclast在他們comment想知道它對另一個答案的方式去做到。

用crontab用戶或/etc/crontab創建文件/tmp/hour

# m h dom mon dow user command 
0 * * * * root /usr/bin/touch /tmp/hour > /dev/null 2>&1 

,然後用它來運行命令:

find /tmp/ -daystart -maxdepth 1 -not -newer /tmp/hour -type f -name "for_one_hour_files*" -exec do_something {} \; 
0

如果你沒有 「-mmin」 你版本的「查找」,那麼「-mtime -0.041667」變得非常接近「在最後一小時內」,所以在你的情況下,使用:

-mtime +(X * 0.041667) 

所以,如果X指6小時,然後:

find . -mtime +0.25 -ls 

作品,因爲24小時* 0.25值爲6小時

1

這裏是爲我工作的方法(和我沒有看到它正在使用以上)

$ find /path/to/the/folder -name *.* -mmin +59 -delete > /dev/null 

刪除所有超過59分鐘的文件,同時保持文件夾不變。

相關問題