Files in a file system are kept track of by so called "index nodes" or "inodes" which store some metadata about each file such as its type, file, access/change/modification/deletion times, owner, group, and so on (not including file names though). Typically, only one file can be associated with a single inode, but this is where hard links come in.
A hard link allows multiple files to be associated with a single inode where one file is a link, and the other is the original file. The key thing is that the link refers to the same inode pointing to the same data. This is different from a soft link, also known as a "symbolic link" or "symlink" which only contains an abstract path to the original file rather than being associated with the original file's inode.
Because of this hard links don't work across multiple file systems or partitions, and they also cannot link to directories. Their biggest advantage, however, is that they stay linked to the original file wherever on the same file system they are, even if the path location of the original file changes (because the link refers to the inode not the path).
In contrast soft links refer to nothing if the original file changes its location, becoming broken links. Their advantage, however, is that they can link across file systems as well as link to directories (because they refer to the path).
To create a hard link to a file use a command like this:
ln /home/user/file.txt /home/user/file-link.txt
The /home/user/file-link will be a hard link to /home/user/file, and will refer to said file even if you move it to /home/user2/file.txt.
To create a soft link or a symlink run the same command, but with an -s option:
ln -s /home/user/file.txt /home/user/file-link.txt
That will create file-link.txt as a link to file.txt, but if you move file.txt from /home/user to /home/user2 the link, still pointing to the original path, will be broken.
Leave a Reply