bash 如何在 Linux 中使用 `find` 命令删除非空目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12488035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:18:40  来源:igfitidea点击:

How can I use the `find` command in Linux to remove non-empty directories?

linuxbashfind

提问by orokusaki

I have temp directories full of junk that all start with __temp__(e.g. __temp__user_uploads), which I want to delete with a cleanup function. My function attempt is to run:

我有一个充满垃圾的临时目录,它们都以__temp__(例如__temp__user_uploads)开头,我想用清理功能将其删除。我的功能尝试是运行:

find . -name __temp__* -exec rm -rf '{}' \;

If I run the command and there are multiple __temp__directories (__temp__fooand __temp__bar), I get the output:

如果我运行命令并且有多个__temp__目录(__temp__foo__temp__bar),我会得到输出:

find: __temp__foo: unknown option

If I run the command and there is only 1 __temp__directory (__temp__foo), it is deleted and I get the output:

如果我运行命令并且只有 1 个__temp__目录 ( __temp__foo),它会被删除并得到输出:

find: ./__temp__foo: No such file or directory

Why doesn't the command work, why is it inconsistent like that, and how can I fix it?

为什么命令不起作用,为什么不一致,我该如何解决?

回答by pilcrow

Use a depth-first search and quote (or escape) the shell metacharacter *:

使用深度优先搜索并引用(或转义)shell 元字符*

find . -depth -name '__temp__*' -exec rm -rf '{}' \;

Explanation

解释

Without the -depthflag, your findcommand will remove matching filenames and then try to descend into the (now unlinked) directories. That's the origin of the "No such file or directory" in your single __temp__directory case.

如果没有该-depth标志,您的find命令将删除匹配的文件名,然后尝试进入(现在未链接的)目录。这就是您的单__temp__目录案例中“没有这样的文件或目录”的起源。

Without quoting or escaping the *, the shell will expand that pattern, matching several __temp__whateverfilenames in the current working directory. This expansion will confuse find, which is expecting options rather than filenames at that point in its argument list.

不引用或转义*,shell 将扩展该模式,匹配__temp__whatever当前工作目录中的几个文件名。这种扩展会混淆find,它在其参数列表中的那个点期待选项而不是文件名。