[unix] What is the difference between a symbolic link and a hard link?

Soft Link:

soft or symbolic is more of a short cut to the original file....if you delete the original the shortcut fails and if you only delete the short cut nothing happens to the original.

Soft link Syntax: ln -s Pathof_Target_file link

Output : link -> ./Target_file

Proof: readlink link Also in ls -l link output you will see the first letter in lrwxrwxrwx as l which is indication that the file is a soft link.

Deleting the link: unlink link

Note: If you wish, your softlink can work even after moving it somewhere else from the current dir. Make sure you give absolute path and not relative path while creating a soft link. i.e.(starting from /root/user/Target_file and not ./Target_file)

Hard Link:

Hard link is more of a mirror copy or multiple paths to the same file. Do something to file1 and it appears in file 2. Deleting one still keeps the other ok.

The inode(or file) is only deleted when all the (hard)links or all the paths to the (same file)inode has been deleted.

Once a hard link has been made the link has the inode of the original file. Deleting renaming or moving the original file will not affect the hard link as it links to the underlying inode. Any changes to the data on the inode is reflected in all files that refer to that inode.

Hard Link syntax: ln Target_file link

Output: A file with name link will be created with the same inode number as of Targetfile.

Proof: ls -i link Target_file (check their inodes)

Deleting the link: rm -f link (Delete the link just like a normal file)

Note: Symbolic links can span file systems as they are simply the name of another file. Whereas hard links are only valid within the same File System.

Symbolic links have some features hard links are missing:

  • Hard link point to the file content. while Soft link points to the file name.
  • while size of hard link is the size of the content while soft link is having the file name size.
  • Hard links share the same inode. Soft links do not.
  • Hard links can't cross file systems. Soft links do.
  • you know immediately where a symbolic link points to while with hard links, you need to explore the whole file system to find files sharing the same inode.

    # find / -inum 517333

    /home/bobbin/sync.sh
    /root/synchro
    
  • hard-links cannot point to directories.

The hard links have two limitations:

  • The directories cannot be hard linked. Linux does not permit this to maintain the acyclic tree structure of directories.
  • A hard link cannot be created across filesystems. Both the files must be on the same filesystems, because different filesystems have different independent inode tables (two files on different filesystems, but with same inode number will be different).