0

Suppose I have a directory foo, another directory foo/bar, and finally a file foo/bar/foobar.

Here's the quirk:

  • If I am in the directory foo and type ln -s bar/foobar . it creates a working symlink.
  • If I am in the directory foo/bar and type ln -s foobar ../ it creates a symlink to the symlink itself, which makes it broken.

I suppose it is somehow related to absolute path vs relative path since ln -s "pwd"/specavg_Pr1_ID15_20160201.fits "pwd"/../ (not actually " but `, but it has a rendering issue) works perfectly.

What I don't understand is, if it were cp or other commands it'd do as what I've expected. But were it not, it would've made huge disasters. What is the difference here, and is there a good habit to ensure my commands reference files correctly? (without referencing with full path all the time...)

1 Answer 1

0

From man 1 ln:

Symbolic links can hold arbitrary text; if later resolved, a relative link is interpreted in relation to its parent directory.

When you do ln -s foobar ../ in foo/bar, the arbitrary text is foobar and the parent directory of the link is ../, i.e. foo/. Therefore the new foo/foobar symlink resolves foobar in foo and points to itself.

See this answer:

[…] GNU coreutils' ln (>= 8.16) support the --relative (or -r) option which means you can call ln -s with 2 absolute or relative (in respect to your working directory) paths and it will figure out the correct relative path that has to be written to the symlink.

If your ln is the GNU ln then try this in foo/bar:

ln -sr foobar ../

and the resulting symlink will be foobar -> bar/foobar. Note the resulting arbitrary text is not what you used in the command. It's what ln -r figured out.

In general (especially if you cannot use -r of the GNU ln) you need to remember how the symlink works: arbitrary text, interpretation in relation to its parent directory. Without -r the arbitrary text comes verbatim from the relevant command line argument.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .