0

I think everyone is familiar with this script:

find /dir1/dir2/dir3/dir4/* -mtime +5 -exec cp -rf {} /dirA/dirB/dirC/ \;

My problem is that I want the contents of dir4 that are older than 5 days, which will be more subdirectories and their contents, to be copied into dirC with their directory structures intact. Sounds good so far and that script should do the job I thought.

But it isn't doing what I thought it should. Instead, it starts in dir1, drills down all the way to the lowest folder and starts copying, then it goes up and starts over in dir4, and so on and so on. The end result is everything in the folder structure is copied multiple times.

I've tried rsync, cpio, and pax in place of cp as well with the same results whether I'm doing rsync -r or cpio -r or pax -r. They all start copying every portion of the directory path.

Any ideas?

1 Answers1

2

You have two problems:

  1. You try to copy a recursive list recursively (double recursion), thereby including files you don't want
  2. You copy without preserving directory structure in relation to the source base directory, thereby ending up with a mangled tree

Instead, you should non-recursively your a recursive list of files to their corresponding directories. You can do this with rsync's --files-from and process substitution:

rsync --from0 --files-from <(find ./src -mtime +5 -print0) \
  ./  ./target

Alternatively, through cpio:

find src/ -mtime +5 -print0 | cpio -0 -o | { cd target && cpio -i; }
that other guy
  • 116,971
  • 11
  • 170
  • 194
  • What if I add -mtime -5 to the script? – Jesse McCullough May 18 '15 at 20:12
  • 1
    @JesseMcCullough You could update the question and explain that you only want to copy files newer than 5 minutes, and include the rsync, cpio and pax commands you tried that didn't work (along with output showing the actual result from each, and an explanation of why that's not what you expected). In general it's better to ask about what you're actually trying to do rather than about [what you got stuck on while trying to do it](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – that other guy May 18 '15 at 20:57