Hard Links and Symbolic Links

Hard links vs soft links

Both hard links and symbolic links act like real files, but are actually pointers to files. However, the differences are based on the way operating systems catalogues files. All of the files on a hard drive are catalogued in data structures called inodes. These data structures store details about the location of bytes on the physical disk the bytes, as well as metadata like the file name, creation date, permissions and others.

A hard link is a pointer to the inode of a file.

Hard links can act like file itself, because it references the same location on the hard drive. If the original file is deleted, moved or renamed, the hard link will still point to the physical location of the bytes; it will remain unaffected by delete, move or rename. If the contents of the file are changed, both the original and hard link will be affected, because they reference the same data. Until all hard links to the file are deleted, the physical location of the data will not be dealocated ( will not be deleted.) Since a hard link is referencing a location on the hard drive, it cannot reference a file outside of it’s file system.

A symbolic link is a special file with it’s own inode that points to the file name of a file.

Symbolic links are files that contain data about the file’s name and location in the file system.

Soft links are an extra layer of indirection on top of normal file access; the kernel has to dereference the link when you open the file, and this takes a small amount of time.

If the original file is moved, renamed, or deleted, the symbolic link file will persist, but will no longer point to anything. All commands referring to the symbolic link are operated on the target of the link. If the symbolic link is deleted, the source file is not affected. However, because a symbolic link is a file that contains data about the name of another file’s inode, it can reference files across file systems, and can be used between separate hard drives.

How to Use Hard Links and Symbolic Links:

On my computer, I have a file called file. I want to create a hard link to it, and a symbolic link to it.

To create a hard link, enter the command ln file _file-symbolic_link

To create a symbolic link, Enter the command ln -s file _file-symbolic_link

Here are the contents of my directory:

Here, I enter some text into the file file and print it to the screen.

Next, I delete the original file and display the contents of the directory:

If I try to display the contents of the file, the hard link still has all of the original file’s data, while the symbolic link is now broken!

References: