What Are Hardlinks and Softlinks (symbolic links) In Linux And How To Create Them

Before understanding what hardlinks and softlinks are, you must have an idea about innodes in Linux Innode is related with hardlinks and softlinks.

What is an Innode?

Innode is a Unix data structure which stores the information about a file or a folder. But innode does not hold the name of the file or a folder but it has an unique id for the file or a folder. Two or more files can possess the same innode id. Thats how hardlinks and softlinks work. Every hard disk has a innode table which stores the information about the files in it. By default there will be enough innodes specific to the disk size to make sure that you wont run out of innodes. However, if you happen to run out of innodes, even if you have storage space, you wont be able to create new files in that hard disk. You can manually increase the innode numbers using some programs, which is out of scope of this tutorial.

So when a user tries to access a file , the innode table retrieves the file using its unique id. So when ever a file is created, it is associated with an innode id.

You can see the innode number of a file using the following command.

sudo ls -i /etc/passwd

You can find the number of innodes avaibale in your file system using the followinf command.

sudo df -i


Soflink is like a pointer to a file. Softlink does not create a copy of a file, but instead it creates a link with the original file in a different name with the same innode entry. So the orinal file and the linked file has the same innode entry. If you delete the original file the link will be lost and you wont be able to view the files using the softlink or symbolic link or symlink. Also if you move the original file to some other location, you wont be able to read the file using soft-link.

Creating A Softlink:

Lets say you have a file named file1 and you want to access the contents of file name using some other name called “file2” from a different location, you create a softlink with file name file2 for file1. You can have the file2 in any other folder. You actuall create a link for a original file in a different location. You can create a softlink using the followinf command.

sudo ln -s ~/demo.text ~/var/www/demo-soft.txt

In the above command i created a softlink demo-soft.txt in /var/www folder for demo.text present in a root folder. demo.txt is the original file and demo-soft.txt is just a link file which is logically linked to demo.text.
Hard Links:

Hard links create exact copy of a file with the same innode entry. Both original and hard linked file will have the same innode id. Unlike softlinks, even if you delete or move the original file you can access the contents from the linked file.

Creating a hard link:

You can create a hard link using the following command.

ln ~/demo.txt ./demo-hard.txt

Other Interesting Blogs

Leave a Comment

Share via
Copy link