As we all know, the ln
command creates a link, with the default being a hard link and the -s
option creating a symlink. The general syntax is ln [-s] OLD NEW
, where OLD is the file you are linking to and NEW is the new file you are creating. Hard links can not be created for directories, as a hard link could be created between folders inside each other & I suppose computers do not yet have the resources to check for this without a SERIOUS slowdown.
When creating the link, the path of both files must be written out, and can be absolute or relative. You can mix relative & absolute filepaths, i.e. have a relative path for the new file/folder & an absolute path for the old one. When creating a hard link with a relative path, the paths of both files are relative to the current folder, while for a symbolic link the path of the linked-to file/folder is relative to its parent folder but the path of the old file/folder is relative to the current folder. Why this is is "relative" to my question.
For example, say we am in the HOME folder, /home/user
, also known as ~
, and create 2 folders, new
and new2
, with the file file
in the folder new
. If we try ln -s new/file new2/file
, the result is a broken link from ~/new2/file
to the currently nonexistent ~/new2/new/file
. However, if we instead run ln -s ../new/file new2/file
, we get the expected result, which is a link from ~/new2/file
to ~/new/file
.
So, my question:
Why is the file path for the OLD file/folder of a symlink relative to its parent, while the other 3 paths (hard link OLD, NEW files, symlink NEW file/folder) are relative to the current folder?
All this is on Fedora, but I'm sure it applies to most UNIX-based OS's.
EDIT E Carter Young seems to hit the nail on the head with regard to my 2nd question (as well as my 1st question, which was wrong anyway). It seems that for a symbolic link, the target doesn't have to exist yet, so the system has to make its path relative to the link rather than the current directory. However, why can't the shell parse out that path when you're running the command, rather than forcing the user to figure out what the path is & enter it him/herself? The shell seems to parse pretty well, so is this a case of legacy issues? Performance issues? What?
link(2)
andsymlink(2)
.touch a; ln a b -s; ln ./a c -s; ln $PWD/a d -s