Hard Link vs Symbolic Link – Understanding the Differences

symbolic-link

As the title says, I would like to know the difference between a hard link and a soft link created by the command ln. The command man ln does provide information, but does not sufficiently answer my question.

Also, it would be nice if someone could provide a setting where hard link might be preferable over a symbolic link.

Best Answer

In Linux/Unix, Shortcuts are known as Links


Links are of two types: soft links (symbolic links) or hard links.

  1. Soft Links (symbolic links)

    You can make links to files and directories, and you can create links (shortcuts) on different partitions and with a different inode number than the original.

    If the real copy is deleted, the link will not work.

  2. Hard Links

    Hard links are for files only; you cannot link to a file on a different partition with a different inode number.

    If the real copy is deleted, the link will work, because it accesses the underlying data which the real copy was accessing.


Question: How do I make soft link?

Answer: A soft link can be made with ln -s; first you need to define the source and then you need to define the destination. (Keep in mind you need to define the full paths of both source and destination; otherwise it will not work.)

 sudo ln -s /usr/lib/i386-linux-gnu/mesa/libGL.so.1 /usr/lib32/libGL.so.1
             (----------Source-------)             ( Destination )

enter image description here

As you can see it has a different inode and can be made on a different partition.


Question: How do I make Hard link?

Answer: A Hard link can be made with ln; first you need to define the source and then you need to define the destination. (Keep it mind you need to define the full path of both source and destination; otherwise it will not work.)

Let's say I have a script in the /script directory named firefox.

 ls -i # Shows you the inode
 5898242 firefox

 ln /scripts/firefox /scripts/on-fire
       ( Source )    ( Destination )

enter image description here

As you can see, it has the same inode. If I delete the original file, the link will still work, and it will act as the original.

enter image description here

Above, I check that the link is working, and then delete the original firefox script.


Question: It would be nice if someone could provide a setting where a hard link might be preferable over a symbolic link.

Answer: Depending on the disk partition layout, hard links have the limitation that they must be on same partition (-1 point) and can only link to files (-1 point), but if the original is deleted, the link will work and it acts like the original (+1 point).

On the other hand, a soft link can point to directories or files (+1 point) and there is no partition limitation (+1 point), but if the source is deleted, the link will not work (-1 point).