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__foo
and __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:
如果我运行该命令并且只有一个__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?
为什么命令不起作用,为什么它不一致,我该如何解决呢?
1 个解决方案
#1
25
Use a depth-first search and quote (or escape) the shell metacharacter *
:
使用深度优先搜索和引用(或转义)shell元字符*:
find . -depth -name '__temp__*' -exec rm -rf '{}' \;
Explanation
说明
Without the -depth
flag, your find
command 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__whatever
filenames 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,它会在参数列表中的那个点上期待选项而不是文件名。
#1
25
Use a depth-first search and quote (or escape) the shell metacharacter *
:
使用深度优先搜索和引用(或转义)shell元字符*:
find . -depth -name '__temp__*' -exec rm -rf '{}' \;
Explanation
说明
Without the -depth
flag, your find
command 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__whatever
filenames 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,它会在参数列表中的那个点上期待选项而不是文件名。