1

I have been searching for a while, but can't seem to get a succinct solution. I am trying to delete old files but excluding some subdirectories (passed via parm) and their child subdirecories.

The issue that I am having is that when the subdirectory_name is itself older than the informed duration (also passed via parm) the find command is including the subdirectory_name on the list of the find. In reality the remove won't be able to delete these subdirectories because the rm command default option is f.

Here is the find commmand generated by the script:

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 

Here is the list of files (and subdirectories brought by the find command)

/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 

Besides this -- the script works fine not bringing (excluding) the files under these 3 subdirectories: subdirectory1, subdirectory2 and subdirectory3.

Thank you.

4

2 回答 2

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
于 2013-06-14T20:55:32.910 回答
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遍历目录和调用rm删除文件系统上的任何文件之间将目录更改为符号链接到另一个目录。可以通过更改-exec partwith-delete-execdir rm -f {} \;如果您find支持它们来缓解。

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

于 2013-06-14T22:15:47.673 回答