3

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.

5
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.

  • Hmm. Possibly add the -l option? I misread the manpage initially, exchanging -l for --copy-links. – Tom Hunt Oct 26 '15 at 16:09
  • 3
    @jofel, you need a trailing / on src in addition to -l as per edit. – Stéphane Chazelas Oct 26 '15 at 16:24
  • From my experience rsync and symlink behavior is very tricky. I can't remember exactly how, but it even makes a difference whether you add the slash at the end of a folder or not. – phk Oct 26 '15 at 16:25
  • @Tom, Sorry, my bad, I replaced -r with -a in my edit, but forgot to remove -l since as -a implies -l. I'll let you fix the mess as you see fittest since it's your answer. You may want to mention running symlinks -cs src beforehand to fix the absolute links and relative symlinks like ../src/inside that do point inside. – Stéphane Chazelas Oct 26 '15 at 16:41
  • I don't think -al breaks anything, but replaced with just -a. I don't have symlinks by default on my system, so don't know about that. I also don't know how rsync determines unsafe or not; I would have expected it to resolve links fully and leave them alone if they do point inside the tree, but haven't tested that. – Tom Hunt Oct 26 '15 at 16:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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