Using Hard Links to Link Files in Linux

Hard links virtually prolferate files without using disk space

Linux Hard Links

Screenshot

A symbolic link is much like a desktop shortcut within Windows. The symbolic link merely points to the location of a file. Deleting a symbolic link has no effect on the physical file that the link is pointing to. A symbolic link can point to any file on the current file system or indeed other file systems. This makes it more flexible than a hard link.

A hard link is the same file that it links to but with a different name.

Why Use Hard Links?

Hard links provide an efficient way to organize files. Imagine you took a picture of a fire engine. You have different folders on your machine as follows:

  • Photos of red things
  • Photos of vehicles
  • Photos of emergency services

You could create a copy of the photo and place it in each of the folders. This means you have three copies of the same file taking up three times the space. Categorizing photos by making copies of them might not take up too much space but if you tried the same thing with videos you would significantly reduce your disk space.

A hard link takes up no space at all. You could, therefore, store the same video in various different categories (i.e. by year, genre, cast, directors) without affecting your disk space.

How to Create a Hard Link

Create a hard link using the following syntax:

ln path/to/file /path/to/hard/link

This is a good way to organize music.

How to Tell the Difference Between a Hard Link and a Symbolic Link

You can tell if a file has a hard link by using the ls command:

ls -lt

A standard file without links will look as follows:

-rw-r--r-- 1 gary gary 1000 Dec 18 21:52 poison.mp3

The columns are as follows:

  • -rw-r--r-- = permissions
  • 1 = number of links
  • gary = group
  • gary = owner
  • 1000 = file size
  • Dec 18 = date
  • 21:52 = time
  • poison.mp3 = filename

If this was a hard link the output would look as follows:

-rw-r--r-- 2 gary gary 1000 Dec 18 21:52 poison.mp3

Notice that the number of links column shows 2. Every time a hard link is created that number will increase.

A symbolic link will look as follows:

-rw-r--r-- 1 gary gary 1000 Dec 18 21:52 poison.mp3 -> poison.mp3

You can clearly see that one file is pointing to another.

How to Find All Hard Links to a File

linux inode values

All files in your Linux system contain an inode number that uniquely identifies the file. A file and its hard link will contain the same inode.

To see the inode number for a file type the following command:

ls -i

The output for a single file will be as follows:

1234567 filename

To find the hard links for a file you just need to do a file search for all the files with the same inode (i.e. 1234567).

You can do that with the following command:

find ~/ -xdev -inum 1234567