Difference between a hard link and a symbolic link

Hugo Bayona
3 min readSep 17, 2019

--

Hard links, Soft Links. Whats the difference?

Soft link

In a few words, a soft link is a file that contains the path to another file, or, in more fancy words, it’s a pointer to another file.

This file is a completely different file, it will not inherit any of the characteristics the original file has.

How to create one

The syntax is very simple:

ln -s original_file soft_link

Hard link

A hard link, on the other hand, is another name you give to a piece of data in your hard drive.

When you create a file and you put a name to it, you just make a hard link.

A new hard link it’s the equivalent of giving two (or more if you create more hard links) names to the same data on the Hard Drive.

https://en.wikipedia.org/wiki/Hard_link

How to create one

The syntax is very simple:

ln original_file hard_link

Example

Let’s do it… initially, we have this:

.
├── folder_1
│ └── original_file
└── folder_2

Now we move to folder_1 and create a hard link and a soft link.

$ cd folder_1
$ ln original_file hard_link
$ ln -s original_file soft_link

If we list folder_1 directory:

$ ls -l
total 8
-rw-rw-r-- 2 vagrant vagrant 13 Sep 17 02:40 hard_link
-rw-rw-r-- 2 vagrant vagrant 13 Sep 17 02:40 original_file
lrwxrwxrwx 1 vagrant vagrant 13 Sep 17 03:00 soft_link -> original_file

Has you can see, the original_file and the hard_link looks exactly the same, that's because they are the same data in the hard drive but with a different name… they even share the same permissions.

The soft_link is just a pointer, to the path of the original_file, but this is a relative path, that means that if you move the file or the link, the link will become invalid.

At this point if we cat the 3 files, all of them will show the same:

$ cat *
Hello, World
Hello, World
Hello, World

But what will happen if we move hard_link and soft_link to the folder_2?

$ mv hard_link ../folder_2/
$ mv soft_link ../folder_2/

Now we have:

.
├── folder_1
│ └── original_file
└── folder_2
├── hard_link
└── soft_link -> original_file

And if we cat everything in folder_2…

$ cat folder_2/*
Hello, World
cat: folder_2/soft_link: No such file or directory

The soft_link immediately stop working.

Finally, let’s see what happen when the original_file is deleted and we try to cat hard_link

$ rm folder_1/original_file
$ rm folder_2/soft_link
$ tree
.
├── folder_1
└── folder_2
└── hard_link
$ cat folder_2/hard_link
Hello, World

I hope this helps you understand the basic difference between a hard link and a soft link, remember to check the ln man page.

--

--