6

I want to retrieve specific files then cp the result into another directory. It is all working, but my command seems to be executed a second time.

For example, I have a file a and I want to cp it into subdirectory test/, so I run:

find . -mtime -1 -name a -exec cp {} test/ ';'

My file is copied into the subdirectory as I wanted but then I get this error message:

cp: './test/a' and 'test/a' are the same file
3
  • seems you already have a file in test, you can limit find to current directory with -maxdepth 1
    – user986805
    Sep 19, 2020 at 13:05
  • or exclude it from the find -name a ! -path './test/*' ...
    – user986805
    Sep 19, 2020 at 13:24
  • there was no file in the test directory prior to the command
    – Saxtheowl
    Sep 19, 2020 at 13:44

1 Answer 1

14

You have a race condition - first find finds ./a and copies it to test/a, then it finds the newly copied ./test/a and tries to copy it again:

$ 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

You could avoid that by telling find not to descend into the target directory ex.

find . -path ./test -prune -o -mtime -1 -name a -exec cp {} test/ ';'
2
  • 5
    I think the term "race condition" is not correct here, because AFAIK there's no concurrency going on and this behavior is determinstic. Sep 20, 2020 at 14:07
  • 1
    @WayneConrad GNU find in its man page does clearly define find to be mono-thread, however the POSIX definition does not mention the fact that find will use a single thread to check the files. So it is possible to implement find to spawn more threads to recursively visit the directories, in which case the behaviour described by the question would actually be a proper race condition. AFAIK neither the POSIX definition nor the GNU man page define ordering of the checks, so this answer would work for both.
    – Bakuriu
    Sep 20, 2020 at 15:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .