Bash脚本可删除超过15个月的文件

时间:2014-04-21 11:29:41

标签: bash shell

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

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

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

这与Bash中的ctime相同吗?

4 个答案:

答案 0 :(得分: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 {} \;

答案 1 :(得分:0)

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

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

答案 2 :(得分: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 {} +

如果-delete支持find,您当然可以使用find a=$(mktemp) touch -d '15 months ago' -- "$a" find "$DIR" -type f \! -newer "$a" \! -samefile "$a" -delete rm -- "$a" 命令。这会给:

{{1}}

答案 3 :(得分:0)

http://linux.die.net/man/8/tmpwatch专为此应用而设计。通常与cron一起使用。