Links

The best way to understand what links are is to look at an example. Let's create a (regular) file:

$ pwd
/home/queen/example
   $ ls
   $ touch a
   $ ls -il a
   32555 -rw-rw-r--    1 queen     queen            0 Dec 10 08:12 a

The -i option of the ls command prints the inode number, which is the first field on the output. As you can see, before we created file a, there were no files in the directory. The other field of interest is the third one, which is the number of file links (well, inode links, in fact).

The touch a command can be separated into two distinct actions:

But now, if we type:

   $ ln a b
   $ ls -il a b
   32555 -rw-rw-r--    2 queen     queen            0 Dec 10 08:12 a
   32555 -rw-rw-r--    2 queen     queen            0 Dec 10 08:12 b
   $

we create another link to the same inode. As you can see, we did not create a file named b. Instead, we just added another link to the inode numbered 32555 in the same directory, and attributed the name b to this new link. You can see on the ls -l output that the link counter for the inode is now 2 rather than 1.

Now, if we do:

   $ rm a
   $ ls -il b
   32555 -rw-rw-r--    1 queen     queen            0 Dec 10 08:12 b
   $

we see that even though we deleted the “original file”, the inode still exists. But now, the only link to it is the file named /home/queen/example/b.

Therefore, a file under UNIX has no name; instead, it has one or more link(s) in one or more directory(ies).

Directories themselves are also stored into inodes, their link count coincides with the number of subdirectories within them. That is due to the fact that there are at least two links per directory: the directory itself (.) and its parent directory (..).

Typical examples of files which are not linked (i.e.: have no name) are network connections; you will never see the file corresponding to your connection to the Mandrake Linux web site in your file tree, no matter which directory you look in. Similarly, when you use a pipe in the shell, the inode corresponding to the pipe exists, but it is not linked. Other use of inodes without names are temporal files. You create a temporal file, open it, and then remove it. The file exists while it is open, but nobody else can open it (as there is no name for opening it). That way if the application crashes, the temporal file is removed automatically.