4

as the answer to this question shows, Is there a difference between hardlinking with cp -l or ln?

The purpose for creating the -l option for the cp command is to recursively hard-link (the contents of) directories. The -s option is the counterpart, creating soft links instead of hard links, but it appears that it can't be used recursively.

Any attempt to do so results in the error message:

cp: `source_dir/source_file': can make relative symbolic links only in current directory

Perhaps this is distro dependent. In Ubuntu 12.04, this is the result. Only if the original file and the link are in the same directory does it work.

Perhaps the syntax is incorrect? cp -rs target_directory destination_directory is what I used.

example:

$ ls sourcedir/             
-rw-rw---- 1 user group 1123 Jan  8 23:10 source_file
$ cp -rs sourcedir/ targetdir/
cp: `targetdir/sourcedir/source_file': can make relative symbolic links only in current directory
anotherguy
  • 483
  • 1
  • 5
  • 9
  • @muru, he isn't trying to. – psusi Jan 08 '15 at 22:27
  • @muru, you can't hard link a directory, which is why cp -l was created: it hard links every individual file in the directory instead. The question though, is why does that work recursively, but doing the same thing with symlinks doesn't. – psusi Jan 08 '15 at 22:31

1 Answers1

4

Given an absolute path to the source directory:

cp -rs $PWD/sourcedir/ targetdir/

The symbolic links in targetdir will then contain absolute paths to sourcedir.

Otherwise, if it just made a symbolic link, it would create something like:

targetdir/filename -> sourcedir/filename

But that isn't the correct relative path to find the original file, it should be:

targetdir/filename -> ../sourcedir/filename

cp doesn't try to figure out how the source and target directories relate to each other, so that it can add the appropriate number of ../ prefixes.

Barmar
  • 9,927