What are some typical uses of hard links in Linux?


To totally unlock this section you need to Log-in


Login

A typical use is for a "backup" reason, for example, if you think that some files, critical, could be deleted accidentally, you can just create hardlinks to those files in another path on your system and stay calm, because even if the original hard links to those files are deleted there will be the others pointing to the original data.

The main advantage of hard links

The main advantage of hard links is that, compared to soft links, there is no size or speed penalty.

Soft links are an extra layer of indirection on top of normal file access; the kernel has to dereference the link when you open the file, and this takes a small amount of time. The link also takes a small amount of space on the disk, to hold the text of the link.

These penalties do not exist with hard links because they are built into the very structure of the filesystem.

What Hard links allow

Hard links allow: a single executable to have more than one filename.

Example:

ls -l /bin | grep -v ' 1 ' | sort


-rwxr-xr-x 2 root root 63 2010-01-19 21:49 gunzip
-rwxr-xr-x 2 root root 63 2010-01-19 21:49 uncompress
-rwxr-xr-x 3 root root 26300 2011-12-12 22:40 bunzip2
-rwxr-xr-x 3 root root 26300 2011-12-12 22:40 bzcat
-rwxr-xr-x 3 root root 26300 2011-12-12 22:40 bzip2

Instead of 3 files bunzip2 bzcat and bzip2 use the same file and inside the file the distinction is made to what to do. Saves code and less code means less possible bugs and easier maintenance.

You can see that bunzip2, bzcat and bzip all use the same inode. In essence, it is one file with three names. You could have three copies of the file, but why? It would only use up disk space unnecessarily.

A link is a directory entry that points to blocks on disk. In other words every file on your system has at least one link. When you rm (remove command on a Unix/Linux system) a file the actual system call is unlink(). It removes the directory entry. The blocks on disk haven't changed but the link is gone, thus the file is gone from the directory listing.

You personally may not ever use hard links, but they are all over your system.

A single file to be accessed by several paths.

Take for example a package manager, that creates a /usr/share/doc/$packagename directory for each package that is installed and inside that directory a file called LICENSE with the license information of the package. Many packages on a typical Linux system are GPL licensed, so instead of having 200 copies of the GPL on the filesystem there could be only one copy and 199 links.