What are Hard Links and Symbolic Links in Linux

How do we create hard links and symbolic links and what is the difference between the two

man page for ln

Hard links and symbolic links

A hard link is an additional name for an existing file in Linux or other Unix-like operating systems.

A symbolic link, also known as a soft link or sym-link, is a special type of file that points to another file.

We use links because they provide an efficient way to organize files.

What is the difference?

Hard link:

  • Can link to a file, but cannot link to a directory.
  • Cannot reference a file that is on a different disk or volume.
  • If you remove the file, the link will still work.
  • The link points to the inode directly, and both the hard link and the linked file share the same inode. An inode stores all the information about a file except its name and its actual data.
  • Contains the data in the target file.

Symbolic link:

  • Can link to a file or to a directory.
  • Can reference a file or a directory that is on a different disk or volume.
  • Is broken if you remove the item that it points to.
  • Points to the object (which then in-turn points to the inode). The inode of the linked file is different from the inode of the symbolic link.
  • Does not contain the data in the target file, but rather, simply points to another entry somewhere in the file system.

Each inode keeps track of the number of hard links pointing to it. Any time you create a file, the number is initialized to 1. When you add a hard link to the same inode, the number will increment by 1. The file is deleted when the number of hard links to it drops to 0.

How do we create a hard link and a symbolic link?

The ln command is used to create hard and symbolic links.

To create a hard link, type: ln <target> <link>

Examples:

lines 5 and 6 show command lines for creating hard link

To create a symbolic link, type: ln -s <target> <link>
(item can be a file or a directory)

Examples:

lines 3 and 4 show command lines for creating symbolic link

To read more about making links between files, type “man ln” in your terminal or google the man page for ln.