Linking files

How Unix thinks about files and directories

It is easy to imagine what a link does, but how it works is equally important. Links can be very useful when properly applied. This section gives some background information.

In chapter 2 we already discussed that there is really no difference between a file and a directory, since a directory is just a file collecting data about other files.

We like to think that files are actually inside of something, inside some special part of the disk that is called a directory. Linking is one place where the real life archive model of a filesystem is wrong.

Every file is represented in the filesystem by an "inode". Think of it as an ID number, or a barcode such as the ones used to identify products in the supermarket. A file gets an inode at the time of creation, and it will remain the same until the file is removed from the system. The inode contains information for the kernel: it stores information on the owner of a file, the location of the data blocks on the disk, and so on. But the system will not know wheter a file is a directory or not until it looks up the file's inode.

Try the GNU ls -if command to display a file's inode:


tille:~/Desktop>ls -if
 293244 ./    293245 .directory   439836 Templates/
  48869 ../   179228 Trash/       374684 Autostart/

tille:~/Desktop>cd Trash/
/nethome/tille/Desktop/Trash

tille:~/Desktop/Trash>ls -if
 179228 ./   293244 ../   179229 .directory
tille:~/Desktop/Trash>

Because the system doesn't know about directories, every directory has to contain the . and .. entries: they contain information about the current directory (single dot, referring to the inodes of files and directories "in" the current directory) and about the parent directory (double dot, the directory that "contains" the current directory).

Hard and soft links

Linking files can be done in two ways:

The ln command

Creating a hard link:

ln filename linkname

Creating a soft link:

ln -s filename linkname

Removing a link is done with the rm command.

Be careful when deleting or moving symbolically linked files: deleting the link leaves the actual file untouched, as might be expected, but deleting the original file leaves an "orphaned" link, pointing to nothing but still using an inode. Be careful when using relative pathnames and be especially careful when linking directories.

Use ls -F or the ls -la to detect links and other special files:


tille@sprawl:~>ls -F .Xdefaults
.Xdefaults@

tille@sprawl:~>ls -la .Xdefaults
lrwxrwxrwx  1 tille tille   27 Apr 30 14:12 .Xdefaults -> /opt/SampleSetup/.Xdefaults