Symbolic links
Recall that a file is represented by a name and by an inode, and
that a single inode can have several names. We use a link
to create an extra name for an inode using the command
ln , so
$ ln fileA fileB
will cause fileA and fileB to be two
names for the same file. If you delete one of them, the other
continues to exist, and the file only disappears when both are
removed. They share the same inode. These hard links can
only be used within a single filesystem. Hard links can also only
be used on ordinary files, and not on directories. If you
try, for instance,
$ ln / rootdirectory
you will get an error message. There is another type of link
referred to as a symbolic link, or soft
link which can get around these problems.
A hard link is an entry in a directory associating a filename
with an inode. A soft link is an entry in a directory associating a
filename with another filename. This is an important distinction -
hard links are names for inodes, soft links are names for other
filenames. To create a soft link, use ln with option
-s ('symbolic'). Consider:
$ ln -s fileA fileB
which will create a symbolic link, called fileB to
a file fileA which should already exist. Examining
your files with ls -l would give something like
lrw-r--r-- 1 chris ugrads 122 May 21 18:40 fileB -> fileA
indicating that fileB is a symbolic link
(l in column 1), and that it points to
(-> ) fileA . Whenever you use
fileB UNIX will assume you want to access
fileA and treat fileB accordingly. If
fileA does not exist, and you try to access
fileB you will get an error message telling you
fileB does not exist. You can make a symbolic link to
any file, provided that the file already exists. The advantage of
symbolic links is that you do not have to worry about the
filesystems the system's storage is divided into. There is a
danger, though: if the file pointed to by a symbolic link is
deleted, the link remains in place. Try:
$ ln -s fileA fileB
$ rm fileA
$ cat fileB
cat: fileB: No such file or directory
Thus you must be careful when deleting files which are pointed
to by symbolic links.
Worked example
In your home directory create a symbolic link called
systmp which is linked to /tmp .
Solution: Use ln -s , as just
described. You cannot use a hard link, since /tmp will
(almost certainly) be on a different filesystem.
$ ln -s /tmp $HOME/systmp
Now try the following to confirm it works:
$ ls $HOME/systmp
$ ls /tmp
|