I need to copy a directory tree full of symlinks to files on a different mount, but buried in the directory are 2 or 3 symlinks to directories outside of the copy tree. I need to copy the symlinks pointing to files as actual files but keep the 2 or 3 symlinks to directories as symlinks.

"scp -L" dereferences everything

I tried "rsync -avHS" followed by "rsync -avHS --keep-dirlinks" or "rsync -avHS -K" but those preserve both file and directory links on the destination so you end up with nothing dereferenced.

2 Answers 2


You could use the Python shutil.copytree function with the symlink parameter set to False and the ignore parameter set to a function that checks for the directory being a symlink (os.path.islink()) and if it isn't returns an empty list but if it is adds the directory and its target (os.readlink) as a tuple to a list of symlinks not followed to recreate later and returns the entire contents list (so ignoring all of the children of the symlink). You could then use the list of symlinks not followed tuples list and os.symlink to create the destination links.

Your Linux distribution is likely to have python already installed.


Here is a Perl script from 2005, "Cleaning up a symlink mess", written by renowned Perl Hacker Randal Schwartz.

Of course it does not exactly do what you want, but it has detailed line-by-line explanations. Maybe you can adapt it to your needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.