Cp command which partially resolves symlinks

backupcpfile-copysymlink

Is there an easy way to copy a directory recursively where
symlinks to external files/directories are resolved (target file is copied),
but internal symlinks (pointing to files inside the copied tree) are kept?

Example:

touch outsidefile
mkdir src
ln -s ../outsidefile src/sym1
touch src/insidefile
ln -s insidefile src/sym2
cp [???] src dest # or other command

wanted result:

$ ls dest
 insidefile
 sym1
 sym2 -> insidefile

i.e. sym1 is a regular file, sym2 keeps to be a symlink.

Best Answer

rsync -a --copy-unsafe-links src/ dest

From the man page:

--copy-unsafe-links

This tells rsync to copy the referent of symbolic links that point outside the copied tree. Absolute symlinks are also treated like ordinary files, and so are any symlinks in the source path itself when --relative is used. This option has no additional effect if --copy-links was also specified.

[...]

--links --copy-unsafe-links Turn all unsafe symlinks into files and duplicate all safe symlinks.

Related Question