Hard Links vs. Symlinks (Symbolic Links)


Hardlinks in Linux vs. Sym Links in Linux

As we are talking about backing up data, and making archives of data, I think it’s important to know the difference between Hard Links and Symbolic LInks in Linux.

Review of hard links

We usually think of a file’s name as being the file itself, but really the name is a hard link. A given file can have more than one hard link to itself–for example, a directory has at least two hard links: the directory name and . (for when you’re inside it). It also has one hard link from each of its sub-directories (the … file inside each one). If you have the stat utility installed on your machine, you can find out how many hard links a file has (along with a bunch of other information) with the command:

stat filename

Hard links aren’t just for directories–you can create more than one link to a regular file too. For example, if you have the file a, you can make a link called b:

ln a b

Now, a and b are two names for the same file, as you can verify by seeing that they reside at the same inode (the inode number will be different on your machine):

ls -i a
  232177 a
ls -i b
  232177 b

So ln a b is roughly equivalent to cp a b, but there are several important differences:

The contents of the file are only stored once, so you don’t use twice the space.
If you change a, you’re changing b, and vice-versa.

If you change the permissions or ownership of a, you’re changing those of b as well, and vice-versa.

If you overwrite a by copying a third file on top of it, you will also overwrite b, unless you tell cp to unlink before overwriting.

Sym Links

Symbolic Links have a slightly different action to them.

Symbolic Links (sometimes call soft links) point to another file, and specifically a file with a specific name.

ln -s test1.txt pointer1.txt

Now, if you catalog pointer1.txt you’ll see teh contents of test1.txt.

cat pointer1.txt

If we now move / rename test1.txt, however, we will end up breaking the link.

mv test1.txt test1-new.txt

Now we can again catalog pointer1.txt, but it won’t be able to find test1.txt and will fail.

cat pointer1.txt

###The Difference

Hard Links point to a node and follow that node throughout, but aren’t a physical copy, so they save space.

Soft links point to a file, and once the file is moved / changed, the link is broken.