How to Create Hard Links in Linux



Linux


In this article, we show how to create hard links in linux.

There are 2 types of links that can be created in linux- hard links and symbolic links.

Hard links are the original Unix way of creating links; symbolic links are more modern.

By default, every file has a single hard link that gives the file its name.

When we create a hard link, we create an additional directory entry for a file.

Hard links have 2 important limitations. One is that a hard link cannot reference a file outside of its own filesystem. This means that a link cannot reference a file that is not on the same disk partition as the link itself. Another is that a hard link cannot reference a directory.

Unlike a directory list containing a symbolic link, a directory list containing a hard link shows no special indication of the link. When a hard link is deleted, the link is removed, but the contents of the file itself continue to exist; space is not deallocated until all links toe the file are deleted.

So this is a summary of hard links, but, again, modern practice prefers symbolic links.

However, in this article, we focus on how to create hard links in linux.

So to create a hard link in linux, we use the following format shown below.



So the code above creates a hard link.

In substitute of file above, you place in the filename that you would like to create a hard link of. For example, this may be the helper.txt file.

In substitute of link above, you create the name for the hard link. For example, this may be helper-copy1.txt. If you want the hard link in another directory, then you specify the path to that directory. For example, if I want to create a hard link of a file in the current directory in the child directory myprojects (in the current directory), then I would specify, myprojects/helper-copy1.txt

In the following code below, there is a file in the current directory named myday.txt.

I create 3 hard links of this file and place in the current working directory. These links are myday-copy1.txt, myday-copy2.txt, and myday-copy3.txt.

Then I create a 4th hard link in the directory, myprojects, called myday-copy4.txt

This is shown below.

Linux

So you can see that there is the original file, myday.txt.

4 hard links of this file are created, in addition to the original file. So, in total, there are 5 links to the file.

When you use the ls -l command to view the files, we see a 5 next to each of the myday.txt files.

This shows that there are 5 links to that file on the computer system.

This is how hard links can be created in linux.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...