为什么我的 find 命令执行两次?

Sax*_*owl 6 command-line bash files find

我想检索特定文件,然后cp将结果放入另一个目录。一切正常,但我的命令似乎被执行了第二次。

例如,我有一个文件a,我想把cp它放到子目录中test/,所以我运行:

find . -mtime -1 -name a -exec cp {} test/ ';'
Run Code Online (Sandbox Code Playgroud)

我的文件被复制到我想要的子目录中,但随后我收到此错误消息:

cp: './test/a' and 'test/a' are the same file
Run Code Online (Sandbox Code Playgroud)

ste*_*ver 15

你有一个竞争条件 - 首先find找到./a它并将其复制到test/a,然后它找到新复制的./test/a并尝试再次复制它:

$ find . -mtime -1 -name a -print -exec cp -v {} test/ ';'
./a
'./a' -> 'test/a'
./test/a
cp: './test/a' and 'test/a' are the same file
Run Code Online (Sandbox Code Playgroud)

您可以通过告诉find不要下降到目标目录 ex来避免这种情况。

find . -path ./test -prune -o -mtime -1 -name a -exec cp {} test/ ';'
Run Code Online (Sandbox Code Playgroud)

  • 我认为术语“竞争条件”在这里不正确,因为 AFAIK 没有并发,这种行为是确定性的。 (5认同)