Bash: Copy named files recursively, preserving folder structure

I was hoping:

cp -R src/prog.js images/icon.jpg /tmp/package

would yield a symmetrical structure in the destination dir:

/tmp
|
+-- package
    |
    +-- src
    |   |
    |   +-- prog.js
    |
    +-- images
        |
        +-- icon.jpg

but instead, both of the files are copied into /tmp/package. A flat copy. (This is on OSX).

Is there a simple bash function I can use to copy all files, including files specified by wildcard (e.g. src/*.js) into their rightful place within the destination directory. A bit like "for each file, run mkdir -p $(dirname "$file"); cp "$file" $(dirname "$file")", but perhaps a single command.

This is a relevant thread, which suggests it's not possible. The author's solution isn't so useful to me though, because I would like to simply provide a list of files, wildcard or not, and have all of them copied to the destination dir. IIRC MS-DOS xcopy does this, but there seems to be no equivalent for cp.


Solution 1:

Have you tried using the --parents option? I don't know if OS X supports that, but that works on Linux.

cp --parents src/prog.js images/icon.jpg /tmp/package

If that doesn't work on OS X, try

rsync -R src/prog.js images/icon.jpg /tmp/package

as aif suggested.

Solution 2:

One way:

tar cf - <files> | (cd /dest; tar xf -)