Hard Links

2023-01-02

The Inspiration Behind This Article

Many users are already familiar with the concept of symbolic links, also known as “symlinks” or “soft links.” These can be thought of as a shortcut of sorts, a separate file that points to another file or directory. While most people are familiar with using soft links, hard links are not as well known or understood. This article aims to enhance your understanding of hard links and how they differ from soft links.

An inode is a uniquely identified number for a file or directory assigned by the Linux kernel. You can view a file’s inode by using ls -i as shown below:

$ ls -i *example_file
3428098 example_file
3428103 symlink_to_example_file

In the example above, you can see the example_file having an inode of 3428098, whereas the symlink created to said file has an inode of 3428103, representing that these are two different files. Every file and directory has an inode assigned to them at the partition level.

Hard links differ due to the fact that they are physically the same file, listed in two different directories. A hard link will have the exact same hash as the original file, meaning the file size, contents and inode are identical. You can remove the original file and the hard link will remain intact, as they are effectively linking to the same data on your partition. For this reason, a hard link must be a file and cannot be a directory, it must also be located on the same partition as the original file.
A hard link example:

$ ls -li *example_file  
3428098 -rw-r--r--. 2 silverblue silverblue 68 Jan  2 19:54 example_file  
3428098 -rw-r--r--. 2 silverblue silverblue 68 Jan  2 19:54 hardlink_to_example_file

You’ll see above, the hard link and the original file both have the exact same inode (3428098), file size (68 bytes) and modification time. Any changes to one file will affect the other, you can think of the original file as a hard link itself.

Hard links offer a number of uses, some examples are:

  • Unlike soft links, moving the original file will not break other hard links
  • Multiple names for the same executable or file
  • Accessing the same file from multiple points