An intro to links in Linux

Link all the things

An intro to links in Linux

In Unix-like systems, it is possible to have a file reference by multiple names. We use links for this, there are two types.

Hard links also allow to point to files, but in a different way than symbolic links. They are the original Unix way of creating links. By default every file has a single hard link that gives the file its name, when we create a hard link, we are creating an additional directory entry for a file. There are two limitations:

  • A hard link cannot reference a file outside of its own file system. The file it is referencing has to be on the same disk partition.
  • A hard link cannot reference a directory.

A hard link is indistinguishable from the file itself. I've listed a directory that contains a hard link and a symbolic link below and we can see that the hard link does not have a special indication that it's a hard link, the symbolic link does (the l in the permissions and the -> showing what it links to)

When a hard link is deleted, the link is removed, but the content of the file itself continue to exist until all links to the file are deleted. You may encounter them from time to time, but modern practice prefers symbolic links.

We can create a hard link by using the following command

ln file link

Symbolic links are a special type of file. They are also called soft links or symlinks They are used to point to any file or directory on any computer, similar to a shortcut in Windows and an alias in Mac OS.

We can create a symbolic link with

ln -s item link

and item can be either a file or directory.

Symbolic links overcome the limitations of hard links because they work by creating a special type of file that contains a text pointer to the referenced file or directory.

If you write something to the symbolic link, the referenced file is written to, when you delete the symbolic link, only the link is deleted and not the file itself. If the file is deleted, the link will continue to exist but will point to nothing and is said to be broken.

Subscribe to madebygps

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.