Hard links and symbolic links are very confusing for Linux beginners. Today we will look at the differences between these two links.
Hard Links In Linux
By default, every file has a single hard link that gives the file its name. When we create a hard link, we create an additional directory entry for a file.
Hard links have two important limitations.
- A hard link cannot reference a file outside its own file system. This means a link cannot reference a file that is not on the same disk partition as the link itself.
- A hard link may not reference a directory.
A hard link is indistinguishable from the file itself. Unlike a symbolic link, when you list a directory containing a hard link, we will see no special indication of the link. When a hard link is deleted, the link is removed, but the contents of the file itself continue to exist (that is, its space is not deallocated) until all links to the file are deleted.
Symbolic Links In Linux
Symbolic links were created to overcome the limitations of hard links. They work by creating a special type of file that contains a text pointer to the referenced file or directory.
In this regard, they operate in much the same way as a Windows shortcut, though of course they predate the Windows feature by many years. A file pointed to by a symbolic link and the symbolic link itself are largely indistinguishable from one another. For example, if you write something to the symbolic link, the referenced file is written to.
When you delete a symbolic link, however, only the link is deleted, not the file itself. If the file is deleted before the symbolic link, the link will continue to exist but will point to nothing. In this case, the link is said to be broken. In many implementations, the ls command will display broken links in a distinguishing color, such as red, to reveal their presence.