1. Overview

On a Linux machine, we can create links to an existing file. A link in Unix can be thought of as a pointer or a reference to a file. In other words, they’re more of a shortcut to access a file. We can create as many links as we want.

In this tutorial, we’ll quickly explore the two types of links: hard and symbolic links. We’ll further talk about the differences between them.

2. Hard Links

A file in any Unix-based operating system comprises of the data block(s) and an inode. The data blocks store the actual file contents. On the other hand, an inode store file attributes (except the file name) and the disk block locations.

A hard link is just another file that points to the same underlying inode as the original file. And so, it references to the same physical file location.

We can use the ln command to create a hard link:

ls -l
-rw-rw-r-- 2 runner3 ubuntu 0 Sep 29 11:22 originalFile

ln originalFile sampleHardLink

ls -l
-rw-rw-r-- 2 runner3 ubuntu 0 Sep 29 11:22 originalFile
-rw-rw-r-- 2 runner3 ubuntu 0 Sep 29 11:22 sampleHardLink

Let’s quickly see their mapped inode numbers:

ls -i
2835126 originalFile
2835126 sampleHardLink

Both of these files point to the same inode. With this, even if we later delete the original file, we’ll still be able to access its contents using the created hard link.

However, please note that we can’t create hard links for directories. Also, hard links cannot cross filesystem boundaries, like between network-mapped disks.

3. Symbolic Links

A symbolic or soft link is a new file that just stores the path of the original file and not its contents. If the original file gets moved or removed, then a soft link won’t work.

Let’s now create a soft or symbolic link:

ln -s originalFile sampleSoftLink

ls -l
-rw-rw-r-- 1 runner1 ubuntu  0 Sep 29 12:16 originalFile
lrwxrwxrwx 1 runner1 ubuntu 12 Sep 29 12:16 sampleSoftLink -> originalFile

Unlike hard links, a soft or symbolic link is a file with a different inode number than the original file:

ls -i
2835126 originalFile
2835217 sampleSoftLink

We’re allowed to create a soft link for a directory. Moreover, with soft links, we can link files across various filesystems.

4. Differences

Now that we understand what a soft or a hard link is, let’s quickly sum up the key differences:

  • A hard link has the same inode number as that of the original file and so can be thought of as its copy. On the other hand, a soft link is a new file which only stores the file location of the original one
  • If the original file gets moved or removed, we can still access its contents using any of its hard links. However, all soft links for that file will become invalid
  • Unlike that of hard links, we can create soft links for directories. Soft links can also span across filesystems

5. Conclusion

In this quick tutorial, we learned about the hard and symbolic/soft links used in all Unix-based operating systems.

Notify of
Inline Feedbacks
View all comments