What is Soft Links and Hard Links in Linux File System

This short post explains what links are and the difference between symbolic (soft) and hard links. A link is a mechanism that allows several filenames to refer to a single file on disk. There are two kinds of links:
1. hard links.
2. symbolic (soft) links.

Hard Links

– A hard link associates two (or more) filenames with an inode.
– Hard links all share the same disk data blocks while functioning as independent directory entries.
– Hard links may not span disk partitions, since inode numbers are only unique within a given device.

Symbolic Links

– A symbolic link is a special file type which points to another file.
– The contents of this special file is the name of the file that it points to.
– Symbolic links are created by the “ln -s“” command.
– Once a file which is pointed to by a symbolic link is deleted, the link still points to it, leaving a hanging link.
– You can use the find command to locate symbolic links:

# find ./* -type l -ls

Examples

1. Consider a file ‘example’ to which there is a hard link ‘hlink’ and a symbolic link ‘slink’. Check the contents of the directory for the file ‘example’:

$ ls -li example
17920190 -rw-rw-r--. 1 user user 0 Nov 18 03:19 example

2. Command to create a hard link to ‘example’ is:

$ ln example hlink

3. Command to create a symbolic link to ‘example’:

$ ln -s example slink

4. Check the contents of the directory again:

$ ls -li
17920190 -rw-rw-r--. 2 user user   0 Nov 18 03:19 example
17920190 -rw-rw-r--. 2 user user   0 Nov 18 03:19 hlink
16836022 lrwxrwxrwx. 1 user user   7 Nov 18 03:21 slink -> example

Notice that both ‘example’ and ‘hlink’ refer to the same inode, but ‘slink’ refers to a different inode.

Difference Between hard link and soft link

Here is a short table of comparison between soft links and hard links.

Parameter Soft Link Hard Link
Length Same as original filename Same as original file length
Inode new inode Same as original file
Restrictions None Same file system; can’t be a directory
Space Length name plus inode Directory entry
Compared to Different Same
Original Deleted Original file remains File remains until last link is deleted
Related Post