2014-04-21 37 views
0

在bash脚本,如果我想删除比在目录15天旧文件,我可以运行:bash脚本文件移除旧的超过15个月

find "$DIR" -type f -mtime +15 -exec rm {} \; 

有人可以帮我一个bash脚本删除目录中超过15个月的文件?

这与Bash中的ctime相同吗?

+0

请参阅http://stackoverflow.com/questions/20034415/bash-delete-all-files-older-than-1-month-but-leave-files-from-mondays?rq=1 –

+0

但是,1月。我没有看到类似于我想要的 – user3409351

+0

-mtime + 65w的解决方案,可能为65周,基于1年是52周,因此一年的四分之一是13周,52 + 13 = 65 –

回答

4

按照手册页:

-mtime n[smhdw] 
     If no units are specified, this primary evaluates to true if the difference between the file last modification time and the time find was started, rounded up to the next 
     full 24-hour period, is n 24-hour periods. 

     If units are specified, this primary evaluates to true if the difference between the file last modification time and the time find was started is exactly n units. Please 
     refer to the -atime primary description for information on supported time units. 

然后,在-atime

-atime n[smhdw] 
     If no units are specified, this primary evaluates to true if the difference between the file last access time and the time find was started, rounded up to the next full 
     24-hour period, is n 24-hour periods. 

     If units are specified, this primary evaluates to true if the difference between the file last access time and the time find was started is exactly n units. Possible 
     time units are as follows: 

     s  second 
     m  minute (60 seconds) 
     h  hour (60 minutes) 
     d  day (24 hours) 
     w  week (7 days) 

     Any number of units may be combined in one -atime argument, for example, ``-atime -1h30m''. Units are probably only useful when used in conjunction with the + or - modi- 
     fier. 

因此,我们有几个星期。 15个月* 4周/月= 60周。

find $DIR -type f -mtime +60w -exec rm {} \; 
+0

是+ 60w相同我正在使用ctime? – user3409351

+2

请注意,15个月可能更像是65周......在此基础上,1年是52周,因此一年中的四分之一是13周,52 + 13 = 65 –

+0

@ user3409351:是的,格式是相同的。正如可以在手册页中看到的那样... – DarkDust

0

使用450(= 15 * 30)作为-mtime参数。

find $DIR -type f -mtime +450 -exec rm {} \; 
+0

如果我使用ctime,那么+ 450是否相同? – user3409351

+0

是的,它是一样的。 –

0

一个有趣的可能性:你可以touch时间戳15 months ago一个tmp文件,并与(否定)-newer标志find使用它:

a=$(mktemp) 
touch -d '15 months ago' -- "$a" 
find "$DIR" -type f \! -newer "$a" -exec rm {} + 
rm -- "$a" 

这当然,假定您touchfind具有这些功能。

如果有可能mktemp在您的目录$DIR的子目录中创建文件,它将变得非常混乱,因为在过程结束之前可以删除引用“$ a”的文件。在这种情况下,100%肯定的是,使用(否定)-samefile测试:

find "$DIR" -type f \! -newer "$a" \! -samefile "$a" -exec rm {} + 

当然你也可以使用find-delete命令,如果您find支持它。这将给:

a=$(mktemp) 
touch -d '15 months ago' -- "$a" 
find "$DIR" -type f \! -newer "$a" \! -samefile "$a" -delete 
rm -- "$a" 
相关问题