What is the difference between a hard link and a symbolic link?

As the title says, I would like to know the difference between a hard link and a soft link created by the command ln. The command man ln does provide information, but does not sufficiently answer my question.

Also, it would be nice if someone could provide a setting where hard link might be preferable over a symbolic link.


Solution 1:

"A picture is worth a thousand words." Pictorial representation


And, "An example is worth a hundred paragraphs..."

Create two files:

$ touch blah1   
$ touch blah2

Enter some data into them:

$ echo "Cat" > blah1
$ echo "Dog" > blah2

And as expected:

$ cat blah1; cat blah2
Cat
Dog

Let's create hard and soft links:

$ ln blah1 blah1-hard
$ ln -s blah2 blah2-soft

Let's see what just happened:

$ ls -l

blah1
blah1-hard
blah2
blah2-soft -> blah2

Changing the name of blah1 does not matter:

$ mv blah1 blah1-new
$ cat blah1-hard
Cat

blah1-hard points to the inode, the contents, of the file - that wasn't changed.

$ mv blah2 blah2-new
$ ls blah2-soft
blah2-soft
$ cat blah2-soft  
cat: blah2-soft: No such file or directory

The contents of the file could not be found because the soft link points to the name, that was changed, and not to the contents.
Similarly, If blah1 is deleted, blah1-hard still holds the contents; if blah2 is deleted, blah2-soft is just a link to a non-existing file.


source: blatantly copying it from StackOverflow!

Solution 2:

A hardlink isn't a pointer to a file, it's a directory entry (a file) pointing to the same inode. Even if you change the name of the other file, a hardlink still points to the file. If you replace the other file with a new version (by copying it), a hardlink will not point to the new file. You can only have hardlinks within the same filesystem. With hardlinks you don't have concept of the original files and links, all are equal (think of it as a reference to an object). It's a very low level concept.

On the other hand, a symlink is actually pointing to another path (a file name); it resolves the name of the file each time you access it through the symlink. If you move the file, the symlink will not follow. If you replace the file with another one, keeping the name, the symlink will point to the new file. Symlinks can span filesystems. With symlinks you have very clear distinction between the actual file and symlink, which stores no info beside the path about the file it points to.