Here we have to face a very common misconception, even among UNIX® users, which is mainly due to the fact that links as we have seen them so far (wrongly called “hard” links) are only associated with regular files (and we have seen that it is not the case — since even symbolic links are “linked”). But this requires that we first explain what symbolic links (“soft” links, or even more often “symlinks”) are.
Symbolic links are files of a particular type whose sole content is an arbitrary string, which may or may not point to an existing file. When you mention a symbolic link on the command line or in a program, in fact, you access the file it points to, if it exists. For example:
$ echo Hello >myfile $ ln -s myfile mylink $ ls -il total 4 169 -rw-rw-r-- 1 queen queen 6 Dec 10 21:30 myfile 416 lrwxrwxrwx 1 queen queen 6 Dec 10 21:30 mylink -> myfile $ cat myfile Hello $ cat mylink Hello
You can see that the file type for
mylink
is l
, for symbolic
Link. The access rights for a symbolic link
are not significant: they will always be rwxrwxrwx
. You
can also see that it is a different file from
myfile
, as its inode number is different. But it
refers to it symbolically, therefore when you type cat
mylink, you will in fact print the contents of the
myfile
file. To demonstrate that a symbolic link
contains an arbitrary string, we can do the following:
$ ln -s "I'm no existing file" anotherlink $ ls -il anotherlink 418 lrwxrwxrwx 1 queen queen 20 Dec 10 21:43 anotherlink -> I'm no existing file $ cat anotherlink cat: anotherlink: No such file or directory $
But symbolic links exist because they overcome several limitations encountered by normal (“hard”) links:
You cannot create a link to an inode in a directory which is on a different file system to the said inode. The reason is simple: the link counter is stored in the inode itself, and inodes cannot be shared between file systems. Symlinks allow do this;
You cannot link directories to avoid creating loops in the file system. But you can make a symlink point to a directory and use it as if it were actually a directory.
Symbolic links are therefore very useful in several circumstances, and very often, people tend to use them to link files together even when a normal link could be used instead. One advantage of normal linking, though, is that you do not lose the file if you delete the “original one”.
Lastly, if you observed carefully, you know what the size of a symbolic link is: it is simply the size of the string.