Easy Relative Symbolic Links

You probably know about the “ln” command to create a new link to an existing file. You probably know about “ln -s” to create a symbolic link. But did you know about “ln -rs” to easily create relative symbolic links? Relative links are often preferable to absolute ones, because that way they stay valid if the whole containing directory tree is moved to a different location (e.g. as the result of a bind mount). But typing the right number of “../” prefixes can get quite fiddly. And if you want to rely on autocomplete to help, you have to change directory to the destination where the symlink is to be created. Instead, a simpler way is to use “ln -rs”, then use autocomplete from wherever you are to get to the right source file/directory, and the ln command will automatically convert the resulting path, whatever it might be (either absolute or relative to your current working directory) to a suitable relative one based on the destination for the link. <https://manpages.debian.org/ln.1.en.html>

On Wed, 1 Nov 2023 18:53:42 +1300, I wrote:
Instead, a simpler way is to use “ln -rs” ...
I discovered a little snag in this. Consider the following sequence: mkdir dir1 dir2 dir3 touch dir1/file ln -rs dir1/file dir2/file ls -l dir2 The output looks like lrwxrwxrwx 1 ldo users 12 Jan 23 16:38 file -> ../dir1/file So far, so good. Next, I try ln -rs dir2/file dir3/file ls -l dir3 I expect the output to look like lrwxrwxrwx 1 ldo users 12 Jan 23 16:38 file -> ../dir2/file Instead, I get lrwxrwxrwx 1 ldo users 12 Jan 23 16:38 file -> ../dir1/file That is to say, ln has first automatically dereferenced the source filename symlink, and then created a symlink to the original item. And there seems to be no option to turn this off. If I avoid the -r option altogether, and do things the old-fashioned way, cd-ing into the destination directory so I can directly specify the symlink as a relative path: (cd dir3; ln -s ../dir2/file file) Then I do indeed get the result I expect: ls -l dir3 producing output lrwxrwxrwx 1 ldo users 12 Jan 23 16:47 file -> ../dir2/file Why is this important? Let’s just say it screwed up the SSL cert config on a webserver, where my symlinks to what were supposed to be the *current* certs ended up pointing to *expired* versions from some prior point in time ...
participants (1)
-
Lawrence D'Oliveiro