unixcp

Copy files from source directory to destination directory, following symlinks in destination directory


I'm trying to copy some files from one directory to another and resolve all symlinks in the destination directory. To better illustrate what I'm saying, my source directory looks something like this:

source
  |-- dir1
  |     `-- file1
  |-- dir2
  |     |-- dir4
  |     `-- file2
  `-- dir3
        `-- file3

And the destination directory:

dest
  |-- dir1
  |-- dir2 -> dir1
  `-- dir3

I want to copy files from source to dest recursively so that after the operation, the destination directory looks like this:

dest
  |-- dir1
  |     |-- dir4
  |     |-- file1
  |     `-- file2
  |-- dir2 -> dir1
  `-- dir3
        `-- file3

I am currently attempting to do this with cp -R source/. dest/ (I can't use the shell glob * for other reasons), and it fails with the error cp: target dest/./dir2 is not a directory. How can I achieve the desired result?

Edit: cannot assume that all directories in source exist in dest.

Edit 2: I could possibly achieve this by creating a tarball of source and extracting it to dest. But that feels really clunky and adding unnecessary steps.


Solution

  • I suggest to use find:

    cd /path/to/source
    find . -type d -exec mkdir -p /path/to/dest/{} \; -o -type f -exec cp {} /path/to/dest/{} \;
    

    (The part for creating directories was added after the question was edited to clarify that directories might not exist in dest.)