When I execute the command find . -mtime -60 I get the list of files modified within the last 60 days.

So when I execute find . -mtime -60 -exec cp {} /tmp/1 \; I can copy these files to a new directory for processing

However if I want to preserve the timestamps, I am unable to copy just the files needed when I execute find . -mtime -60 -exec cp -LR --preserve=timestamps {} /tmp/2 \;

What ends up happening is that ALL files in the source directory are copied instead of just the files I need.

Any solution here?


What is happening here is that when you use the -R option to cp and supply a directory as an argument, it copies everything in that directory. Moreover, this will not preserve the directory structure as any files in lower directories will be copied directly to /tmp/2. This may be what you want (see X Tian's answer for how to do it this way), but beware if any files have the same name, one will overwrite the other at the detination.

To preserve the directory structure, you can use cpio:

find . -mtime -60 -print0 | cpio -0mdp /tmp/2

If the -0 (or equivalent) option is unavailable, you can do this, but be careful none of your file names contains a newline:

find . -mtime -2 | cpio -mdp /tmp/2

cpio should also support the -L option, although be careful with this as in some cases it can cause an infinite loop.

| improve this answer | |

You should exclude directories, the first file find prints is . in addition you use the recursive option on the copy.

So following is more what you intended, however as Graeme points out, cpio -pdm will preserve the original directory structure, cp will only copy into destination directory.

find . -mtime -60 -type f -exec cp -Lv --preserve=timestamps {} /tmp/2 \;

I'm leaving this answer to highlight the difference between Graeme and this solution. Since I do think it adds something to the overall answer to original question. Other readres might find this interesting.

| improve this answer | |
  • You are better using + instead of \; as what you are doing will invoke one cp per file, this is not necessary. Also, this won't preserve the directory structure and may lead to some files overwriting each other if they have the same name. – Graeme Mar 7 '14 at 1:07
  • Great comment, You are absolutely correct on all 3 accounts. I'll update just to highlight the recursive, directory error. – X Tian Mar 7 '14 at 7:38

This preserves timestamps across directories and files:

find . -mtime -60 -type f -exec cp --parents -fuav {} /tmp/2 \;

Tested using CentOS 7.2.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.