I have directory that contains some symbolic links:

user@host:include$ find .. -type l -ls
4737414    0 lrwxrwxrwx   1 user group       13 Dec  9 13:47 ../k0607-lsi6/camac -> ../../include
4737415    0 lrwxrwxrwx   1 user group       14 Dec  9 13:49 ../k0607-lsi6/linux -> ../../../linux
4737417    0 lrwxrwxrwx   1 user group       12 Dec  9 13:57 ../k0607-lsi6/dfc -> ../../../dfc
4737419    0 lrwxrwxrwx   1 user group       17 Dec  9 13:57 ../k0607-lsi6/dfcommon -> ../../../dfcommon
4737420    0 lrwxrwxrwx   1 user group       19 Dec  9 13:57 ../k0607-lsi6/dfcommonxx -> ../../../dfcommonxx
4737421    0 lrwxrwxrwx   1 user group       17 Dec  9 13:57 ../k0607-lsi6/dfcompat -> ../../../dfcompat

I need to copy them to the current directory. The resulting links should be independent from their prototypes and lead directly to their target objects.

  • cp -s creates links to links that is not appropriate behavior.
  • cp -s -L refuses to copy links to directories
  • cp -s -L -r refuses to copy relative links to non-working directory

What should I do?


Solution 1:

cp --preserve=links

From the man page:

   --preserve[=ATTR_LIST]
          preserve  the   specified   attributes   (default:   mode,owner-
          ship,timestamps),  if  possible  additional attributes: context,
          links, xattr, all

Personally, I use cp -av for most of my heavy copying. That way, I can preserve everything - even recursively - and see the output. Of course, that is just personal preference.

As to why your other options did not do what you expected, -s makes a link instead of copying and -L follows the links in the source to find the file to copy instead of copying the links themselves.

Solution 2:

Just as the man page says, use -P. This setting says:

-P, --no-dereference
       never follow symbolic links in SOURCE

Solution 3:

If the links contain relative paths, then, copying the link will not adjust the relative path. Use readlink, with the switch -f to follow recursively, in order to get the absolute path of the link. For example:

ln -s $(readlink -f old/dir/oldlink) new/dir/newlink

If preserving the relative paths is what you want, than the option -P of cp, as said by Ignacio Vazquez-Abrams, is what you need.