简体   繁体   English

非零返回代码虽然找到-exec rm工作

[英]nonzero return code although find -exec rm works

I'm on a linux system I wonder what is wrong with the following execution of find: 我在Linux系统上我想知道以下执行find有什么问题:

mkdir a && touch a/b                      
find . -name a -type d -exec echo '{}' \; 
./a
find . -name a -type d -exec rm -r '{}' \;
find: `./a': No such file or directory

The invocation of echo is just for testing purposes. echo的调用仅用于测试目的。 I would expect the last command to remove the directory './a' entirely and return 0. Instead it removes the directory and generates the error message. 我希望最后一个命令完全删除目录'./a'并返回0.而是删除目录并生成错误消息。 To repeat, it does remove the directory! 重复一遍,它确实删除了目录! What is going on? 到底是怎么回事?

rm executes without a problem. rm执行没有问题。 The issue is that find is confused, since it knew the directory ./a was there, it tries to visit that directory to look for directories named a . 问题是find很困惑,因为它知道目录./a在那里,它试图访问该目录以查找名为a目录。 However, find cannot enter the directory, since it was already removed. 但是,find无法进入目录,因为它已被删除。

One way to avoid this is to do 避免这种情况的一种方法是这样做

find -name a -type d | xargs rm -r

This will let the find move along before the rm command is executed. 这将使查找在rm命令执行之前移动。 Or, you can simply ignore the error in your original command. 或者,您可以简单地忽略原始命令中的错误。

Based on epsalon's comment the solution is to use the -depth option which causes the deeper files to be visited first. 根据epsalon的评论,解决方案是使用-depth选项,这会导致首先访问更深层的文件。

find . -depth -name a -type d -exec rm -r '{}' \;

does the trick. 诀窍。 Thanks a bunch! 谢谢你!

如果性能是个问题,请使用-prune以防止find降级到名为“a”的目录:

find . -name a -type d -prune -exec rm -r '{}' \;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM