Hard links vs soft links in Linux


Nitin Venkatesh's Gravatar

Nitin Venkatesh
published April 30, 2015, 9:02 p.m.


There are two types of links in the Linux world that you'll come across - hard links and soft links. Hard links are the source files in a different location (think, a wormhole bending space and time and being at two places at once), whereas soft links(or symbolic links) act as pointers to the original file.

Live Action Zone

Let's create a text file for experimenting called 1.txt

$ echo "1" > 1.txt
$ echo "1 again" >> 1.txt

$ cat 1.txt 
1
1 again
Syntax: ln [-s] source_file link_file

Next, let's create hard and soft links to the 1.txt file we just created.

$ ln 1.txt 1_link_hard
$ ln -s 1.txt 1_link_soft

$ ls -li 1*
554153 -rw-rw-r-- 3 nitin nitin 0 Nov  8 18:37 1_link_hard
531592 lrwxrwxrwx 1 nitin nitin 5 Apr 30 22:17 1_link_soft -> 1.txt
554153 -rw-rw-r-- 3 nitin nitin 0 Nov  8 18:37 1.txt

We notice a few things:

  • Soft links are indicated by a l in the permissions section.
  • Soft links have an arrow mark (->) pointing to the source.
  • Soft links have a different inode number compared to the source.
  • Hard links have the same inode number as the source.
$ cat 1_link_hard 
1
1 again

$ cat 1_link_soft
1
1 again

Everything looks normal, moving on.

$ echo "1 from hard_link" >> 1_link_hard
$ echo "1 from soft link" >> 1_link_soft

$ cat 1.txt 
1
1 again
1 from hard_link
1 from soft link

Everything looks normal, moving on.

$ rm 1.txt

$ ls -l
-rw-rw-r-- 3 nitin nitin 0 Nov  8 18:37 1_link_hard
lrwxrwxrwx 1 nitin nitin 5 Apr 30 22:17 1_link_soft -> 1.txt

$ cat 1_link_soft 
cat: 1_link_soft: No such file or directory

$ cat 1_link_hard 
1
1 again
1 from hard_link
1 from soft link

This is where a hard link stands out from a soft link. The soft link dies the moment the source is gone leaving behind a corpse (a dead link that points to nowhere), but a hard link lives on even after the source is deleted.

Summary:

Hard links:

  • Are literally the source files.
  • Exist even after the source file is deleted.
  • Have the same inode number as the source file.
  • Cannot be created across partitions.

Soft links:

  • Are simple pointers to the source file.
  • Die as soon as the source file is deleted, leaving behind a corpse (dead link)
  • Have a different inode number than the source file.
  • Can be created across partitions.