5

Let's suppose I have one file and one directory:

$ ls -l
total 4
drwxrwxr-x. 2 user user 4096 Oct  8 09:53 dir
-rw-rw-r--. 1 user user    0 Oct  8 09:53 file

I created a symlink to file called symlink1, and a symlink to dir called dirslink1:

$ ls -l
drwxrwxr-x. 2 user user 4096 Oct  8 09:53 dir
lrwxrwxrwx. 1 user user    3 Oct  8 10:03 dirslink1 -> dir
-rw-rw-r--. 5 user user    0 Oct  8 09:53 file
lrwxrwxrwx. 1 user user    4 Oct  8 09:53 symlink1 -> file

Now I created symlinks to symlink1 using ln -s and ln -sL:

$ ln -s symlink1 symlink2
$ ln -sL symlink1 symlink3
$ ln -s dirslink1 dirslink2
$ ln -sL dirslink1 dirslink3

Now, as far as I understand, symlink3 should point to file and dirslink3 should point to dir. But when I check it, none of the symlink[23] and dirslink[23] points to the original file or dir:

$ ls -l
drwxrwxr-x. 2 user user 4096 Oct  8 09:53 dir
lrwxrwxrwx. 1 user user    3 Oct  8 10:03 dirslink1 -> dir
lrwxrwxrwx. 1 user user    9 Oct  8 10:03 dirslink2 -> dirslink1
lrwxrwxrwx. 1 user user    9 Oct  8 10:03 dirslink3 -> dirslink1
-rw-rw-r--. 5 user user    0 Oct  8 09:53 file
lrwxrwxrwx. 1 user user    4 Oct  8 09:53 symlink1 -> file
lrwxrwxrwx. 1 user user    8 Oct  8 09:54 symlink2 -> symlink1
lrwxrwxrwx. 1 user user    8 Oct  8 09:54 symlink3 -> symlink1

The question is: Is it possible/How do I create a symlink to the original file using another symlink?

wjandrea
  • 658
mrc02_kr
  • 2,003

2 Answers2

10

-L only works with hard links; as specified in POSIX:

If the -s option is specified, the -L and -P options shall be silently ignored.

If you have readlink you can use that:

ln -s -- "$(readlink symlink1)" symlink4

If your readlink supports the -f option, you can use that to fully canonicalise the target (i.e. resolve all symlinks in the target’s path, if the target symlink includes other symlinks).

Stephen Kitt
  • 434,908
5

You can use cp -P to make a copy of a symlink:

cp -P symlink2 symlink3

(assuming symlink3 doesn't already exist as a directory or symlink to directory, see the -T option with GNU cp for those cases).

Beware that if the target of the symlink is relative, the above would probably result in a broken link if the copy is not in the same directory as the original.

With zsh,

ln -s -- symlink2(:P) symlink3

Would create symlink3 as a symlink to the full canonical (symlink-free) path of symlink2, like ln -s -- "$(readlink -f symlink2)" symlink3 but more reliable in that it would still work correctly if that path ended in newline characters.

Same caveat as above and same work around with GNU ln.