Understanding Hard link in Linux

Understanding Hard link in Linux

The concept of a hard link is the most basic thing and here we will discuss it today.

Every file on the Linux filesystem starts with a single hard link.

What is the hard link?

The link is between the filename and the actual data stored on the filesystem.

Creating an additional hard link to a file means a few different things. Let’s discuss these.

First, you create a new filename pointing to the exact same data as the old filename. This means that the two filenames, though different, point to identical data. For example, if I create a file

"/home/eduguru.in/demo/link_test"

and write hello world in the file, I have a single hard link between the filename  "link_test" and the file content hello world.

[tcarrigan@server demo]$ ls -l
total 4
-rw-rw-r--. 1 eduguru.in eduguru.in 23 Jul 29 14:27 link_test

Take note of the link count here (1).

Next, I create a new hard link in /tmp to the exact same file using the following command:

[tcarrigan@server demo]$ ln link_test /tmp/link_new

The syntax is ln (original file path) (new file path).

Now when I look at my filesystem, I see both hard links.

[tcarrigan@server demo]$ ls -l link_test /tmp/link_new 
-rw-rw-r--. 2 eduguru.in eduguru.in 23 Jul 29 14:27 link_test
-rw-rw-r--. 2 eduguru.in eduguru.in 23 Jul 29 14:27 /tmp/link_new

The primary difference here is the filename. The link count has also been changed (2). Most notably, if I cat the new file’s contents, it displays the original data.

[eduguru@server demo]$ cat /tmp/link_new 
hello world

When changes are made to one filename, the other reflects those changes. The permissions, link count, ownership, timestamps, and file content are the exact same. If the original file is deleted, the data still exists under the secondary hard link. The data is only removed from your drive when all links to the data have been removed. If you find two files with identical properties but are unsure if they are hard-linked, use the  “ls -i" command to view the inode number. Files that are hard-linked together share the same inode number.

[eduguru@server demo]$ ls -li link_test /tmp/link_new 
2730074 -rw-rw-r--. 2 eduguru.in eduguru.in 23 Jul 29 14:27 link_test
2730074 -rw-rw-r--. 2 eduguru.in eduguru.in 23 Jul 29 14:27 /tmp/link_new

The shared inode number is 2510011, meaning these files are identical data.

 

Limitation of Hard Link

While useful, there are some limitations to what hard links can do. For starters, they can only be created for regular files (not directories or special files). Also, a hard link cannot span multiple filesystems. They only work when the new hard link exists on the same filesystem as the original.