Symbolic Links & Hard Links

If you’re new to working with Linux or other Unix-like OS, you’ve likely encountered symbolic links and hard links, so it’s a good idea to familiarize yourself with what they are. We’ll take a look at their descriptions, when and why they’re used, and how to create them.
Definitions
A hard link is a human-readable name that a file or directory* is referenced by. Most files have one hard link, but on many operating systems it is possible to create multiple hard links to a file. Creating additional hard links will associate more than one name, or alias, to a given file. Because a hard link directly references a piece of data, any changes made to a hard link affect all other hard links which reference that data. Removing all hard links to a file will render that data inaccessible, and effectively deleted.**
A symbolic link (aka soft link, or symlink), is a file which contains the path (location) of another file (or directory). The file being pointed to is called the target. The path information is contained as a text string. A symbolic link is independent of its target, so deleting the symbolic link will not delete the target. However, deleting the target will result in an orphaned or dangling link, which points to a target which does not exit.
*While technically possible, creating more than one hard link to a directory could result in breaking the tree structure of a filesystem, and is consequently often forbidden
**If the file has no hard links and is not accessed by any running processes, the location containing the data will be marked as available space, but the data will remain until overwritten
Application
Both types of links can be used to make “copies” of a file without increasing the amount of disk usage. But because hard links directly reference data in a filesystem, there is no overhead when using them. On the contrary, opening a file via a symbolic link requires the symlink to be dereferenced before the file is opened, which uses a small amount of CPU, and the symlink also consumes a small amount of storage space.
Since symbolic links are unique files from their respective targets, they can be used to specify a different set of permissions from the target’s hard links. They can also make referencing a file easier. If multiple references to one file are needed, using a symbolic link ensures that if the target is ever moved, only the symbolic link needs to be updated, and not all of the references to the file.
Examples
To create a hard link on Linux, the ln
command may be used:
ln file.demo hardlink.demo
This code creates a hard link to “file.demo” called “hardlink.demo”.
To create a symbolic link on Linux, use ln
with the either the -s
or--symbolic
option:
ln -s file.demo symlink.demo
This code creates a symbolic link to “file.demo” called “symlink.demo”.
Sources: