Last Updated: February 25, 2016
·
440
· pvdb

Duplicate (~ "copy") a symlink on Unix

the problem

Using a naked cp command will create an actual file copy of the target of the symlink, as opposed to a new symlink pointing to the same target.

solution #1

Use a combination of ln and readlink, as in this example:

ln -s $( readlink <existing_symlink> ) <duplicate_symlink>

This creates <duplicate_symlink> as a new symlink with the same target as <existing_symlink>.

solution #2

The same can be achieved with cp, but only if the correct options are used, as in this example:

cp -R -P <existing_symlink> <duplicate_symlink>

Note that both the -R and -P options need to be specified in this case in order to be fully portable.


example #1

$ readlink /usr/local/bin/gtac
../Cellar/coreutils/8.24/bin/gtac
$ ln -s $( readlink /usr/local/bin/gtac ) /usr/local/bin/tac
$ readlink /usr/local/bin/tac
../Cellar/coreutils/8.24/bin/gtac
$ _

example #2

$ readlink /usr/local/bin/gtac
../Cellar/coreutils/8.24/bin/gtac
$ cp -R -P /usr/local/bin/gtac /usr/local/bin/tac
$ readlink /usr/local/bin/tac
../Cellar/coreutils/8.24/bin/gtac
$ _