项目中需要写一个shell script,删除某个文件夹中N天以前的文件。本来以为比较简单,可是实际写起来还是发现了一些问题。
主要的思路如下:
find . -mtime n -exec rm -f {} \;
即首先找到当前目录中最近修改时间在N天以外的文件,然后删除这些文件。但在网上找了一些资料,关于-mtime的参数到底该如何设置,还是有些疑问。
用man find找到的相关解释:
-mtime n True if the file modification time subtracted
from the initialization time is n-1 to n
multiples of 24 h. The initialization time
shall be a time between the invocation of the
find utility and the first access by that
invocation of the find utility to any file
specified in its path operands.
说-mtime n将会找到24*(n-1)到24*n个小时之间修改过的文件。
以下是当前目录当中的文件和它们的创建时间,当前时间为Aug 17 15:37:55.
输入以下几个命令进行测试,
$ find . -mtime 1 #注:找到24~24*2小时之间修改的文件
./log_2
$ find . -mtime 2 #注:找到24*2~24*3小时之间修改的文件
./log_3
$ find . -mtime 3 #注:找到24*3~24*4小时之间修改的文件
./log_4
$ find . -mtime +1 #注:找到24*2小时以前修改的文件
./log_3
./log_4
./log_5
./log_6
$ find . -mtime +2 #注:找到24*3小时以前修改的文件
./log_4
./log_5
./log_6
$ find . -mtime +3 #注:找到24*4小时以前修改的文件
./log_5
./log_6
$ find . -mtime 0 #注:找到24小时以内修改的文件
.
./log_1
$ find . -mtime -1 #注:找到24小时以内修改的文件
.
./log_1
$ find . -mtime -2 #注:找到24*2小时以内修改的文件
.
./log_1
./log_2
经过以上测试,可以得到以上的结论:
-mtime n: 找到24*n~24*(n+1)小时之内修改的文件
-mtime +n: 找到24*(n+1)小时以前修改的文件
-mtime 0: 找到24小时以内的修改过的文件
-mtime -n: 找到24*n小时以内修改过的文件
因此,比如要删除3天,即24*3小时以前的数据,则应该使用一下语句:
find . -mtime +2 -exec rm -f {} \;
这和man find中的说明不太一致,目前还不知道是什么原因。