查找和删除旧文件(不包括某些子目录)

时间:2013-06-14 20:52:40

标签: shell unix directory

我一直在寻找,但似乎无法得到一个简洁的解决方案。我试图删除旧文件,但不包括一些子目录(通过parm传递)和他们的子子目录。

我遇到的问题是,当subdirectory_name本身早于通知的持续时间(也通过parm传递)时,find命令会在find列表中包含subirectory_name。实际上,删除将无法删除这些子目录,因为rm命令默认选项为f

以下是脚本生成的查找命令:

find /directory/ \( -type f -name '*' -o -type d \
    -name subdirectory1 -prune -o -type d -name directory3 \
    -prune -o -type d -name subdirectory2 -prune -o \
    -type d -name subdirectory3 -prune \) -mtime +60 \
    -exec rm {} \; -print 

以下是文件列表(以及find命令带来的子目录)

/directory/subdirectory1  ==> this is a subdreictory name and I'd like to not be included   
/directory/subdirectory2  ==> this is a subdreictory name and I'd like to not be included      
/directory/subdirectory3  ==> this is a subdreictory name and I'd like to not be included        
/directory/subdirectory51/file51               
/directory/file1 with spaces 

除此之外 - 脚本工作正常,不会带来(排除)这3个子目录下的文件: subdirectory1subdirectory2subdirectory3

谢谢。

2 个答案:

答案 0 :(得分:2)

以下命令将仅删除超过1天的文件。 您可以排除目录,如下面的示例所示,目录test1& test2将被排除在外。

find /path/ -mtime +60 -type d \( -path ./test1 -o -path ./test2 \) -prune -o -type f -print0 | xargs -0 rm -f 

虽然建议使用-print

查看要删除的内容
find /path/ -mtime +60 -type d \( -path ./test1 -o -path ./test2 \) -prune -o -type f -print

答案 1 :(得分:0)

find /directory/ -type d \(
    -name subdirectory1 -o \
    -name subdirectory2 -o \
    -name subdirectory3 \) -prune -o \
    -type f -mtime +60 -print -exec rm -f {} +

请注意,AND运算符(-a,如果未指定,则隐含在两个谓词之间)优先于OR(-o)。所以上面就像是:

find /directory/ \( -type  d -a \(
    -name subdirectory1 -o \
    -name subdirectory2 -o \
    -name subdirectory3 \) -a -prune \) -o \
    \( -type f -a -mtime +60 -a -print -a -exec rm -f {} + \)

请注意,每个文件名都与*模式匹配,因此-name '*'-true类似,没有用处。

使用+代替;运行较少的rm命令(尽可能少,并且每个命令都会传递几个要删除的文件)。

不要在其他人可写的目录上使用上面的代码,因为它很容易受到攻击,攻击者可以在find遍历目录并调用{{1}的时间之间将目录更改为符号链接到另一个符号链接你要删除文件系统上的任何文件。如果rm支持-exec part -delete,可以通过更改-execdir rm -f {} \;来缓解此问题。

如果要排除特定find而不是名称为-path的任何目录,请参阅subdirectory1谓词。

相关问题