What is the difference between hard links and symbolic links?

Operating systems like Unix and Linux allow the creation of pointers specifically meant for files. This means that we can establish links between files.

However, there are different ways to create links, such that the mechanisms used at the backend differ starkly. Furthermore, the implications for different kinds of links depend, again, on the kind of link between files.

There are two distinct kinds of links that can be created:

  • Hard links

  • Soft (symbolic) links

Let's discuss each of these in detail.

Hard links

Files with hard links are referenced to the same inode value. The same inode value means the files are mapped onto the same physical address location on the disk.

Note: To learn more about inodes, we can refer to the inode section of this Answer.

For instance, two hard-linked files mean that a separate inode is created that points to both of the hard-linked files.

Hard linking between two different files

Properties

Hard links demonstrate the following properties:

  • Changing the name of any hard-linked files does not affect the hard link.

  • The link still contains the data if the original file is removed, because hard links store actual data values.

  • Changes made in any hard-linked file are reflected across all hard-linked files.

Hard links can be created between two files using the following terminal command:

ln file_one.txt file_two.txt

Soft (symbolic) links

Files with soft links, also known as symbolic links, are referenced so that one file is linked to another. A pointer is created that translates one file name to another file name. Referring to one file symbolically linked to another simply translates the former file name to the latter file name.

For instance, if file_a is symbolically linked to file_b, then referring to file_b would simply map to file_a and refer to the content of file_a.

Soft linking between two different files

Properties

Soft links demonstrate the following properties:

  • Soft linking contains the link to the file only, and not the actual contents of the file.

  • Removing the original file causes its pointer to point to nothing, forming a dangling pointer.

  • Soft links have the same size as that of the original file.

Hard links can be created between two files using the following terminal command:

ln -s file_one.txt file_two.txt

Usage of links

Links are used to link libraries and create duplicates of the required files without moving them from their original location. This allows the usage of multiple files in different locations without making the file structure tedious to understand.

Copyright ©2024 Educative, Inc. All rights reserved