2008-10-30 65 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分钟的文件,同时保持文件夹不变。

相关问题