Too many copies of folders and files

185 views Asked by At

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

There are 1 answers

2
that other guy On

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; }