Hard link

From MEPIS Documentation Wiki

Jump to: navigation, search

Hard link is in fact nothing more than the usual file name. The only unusual thing is that file can have more than one such name. The additional names are created as hardlinks, but once created, all these hardlinks/names are totally equal.

In more detail, hard link is a reference, or pointer, to physical data on a storage volume. On most file systems, all named files are hard links. The name associated with the file is simply a label that refers the operating system to the actual data. As such, more than one name can be associated with the same data. Though called by different names, any changes made will affect the actual data, regardless of how the file is called. Hard links can only refer to data that exists on the same file system.

Basically, if you create a hard link you create an additional name for the file (root can even create an additional name for a folder), if you delete the last hard link you delete the associated file too (file no longer exists under any name).

(If still in use by a running program, file can survive for some time even without any name - sometimes you can observe this when deleting huge file to make free space, being puzzled why the free space did not increase.)

To create a hard link you can use the ln command:


This creates a link to TARGET with the name LINK_NAME. TARGET can be either a folder or a file. For more information about the command type in terminal:

man ln 

However, useful hardlinks are often created using another command, cp -l .... The -l option instruct the cp command to save space using hardlinks. Instead of copying the data itself, it just makes them reappear under an additional name. The result is in practice quite similar to the true copy. One useful example is making a cheap 'backup' of a folder in which we plan extensive cleanup consisting of deleting, moving and renaming files. The command is:

 cp -la folder folder.bak

The operation is very quick and few additional space is used as in fact no files are copied, they all just get additional names (for subfolders, a real copy is made, but files in them are again just hardlinks). Then we can do the housekeeping using rm and mv. Removed files still have the second name in folder.bak and therefore we can recover them if needed. Once we are sure everything is OK, we can remove folder.bak and make really disappear everything we deleted.

One problem with this 'backup' is that it is not sure what happens when we edit the files. When saving edited files, some text editors delete the old file and create a new one. Backup stays unchanged in this case. It is however also possible for the text editor to rewrite the file, changing it under both names.

Personal tools
In other languages