Copy symlink AND where it points to using rsync

rsyncsymlink

It doesn't need to be done by rsync, but it would be nice not have to write a script to do this, and rsync is very close to what I want.

rsync -a (or -l) can preserve symlinks, and -L can dereference symlinks and copy it as if it is normal file/dir. However, is it possible to keep the symlink, and also copy the files/directories the links points to?

Here's an example. Say we have this folder hierarchy:

dirA/link_to_file -> ../dirB/file
dirA/link_to_dir -> ../dirC
dirB/file
dirB/not_this_file
dirC/file
dirC/file2
dirD/others

and when I do rsync -aR dirA dest (or something else), I'd like to have exactly these appear in dest:

dirA/link_to_file -> ../dirB/file
dirA/link_to_dir -> ../dirC
dirB/file
dirC/file
dirC/file2

Is this possible with rsync? Thank you.

Let's assume symlinks having absolute path or pointing to outside the source directory can be ignored.

Best Answer

If you know the symlink name and want to transfer the link and the target you can:

rsync -a 'symlink' .
realdir="$(basename "$(readlink -f 'symlink')")"
rsync -a "$realdir" .

The first rsync transfers just the symlink. The second command finds the real directory name, and the second rsync transfers the directory content.

Related Question