Hard Links and Soft Links With Detailed Example In Ubuntu Linux

This is a detailed example to learn the difference between hard links and soft links in Linux.


Create two files:

$ touch foo; touch bar

Enter some Data into them:

$ echo "Cat" > foo
$ echo "Dog" > bar

And as expected:

$cat foo; cat bar
Cat
Dog

Let's create hard and soft links:

$ ln foo foo-hard
$ ln -s bar bar-soft

Let's see what just happened:

$ ls -lrt
total 24
-rw-r--r--  2 aaa  staff  4 Dec 12 21:52 foo-hard
-rw-r--r--  2 aaa  staff  4 Dec 12 21:52 foo
-rw-r--r--  1 aaa  staff  4 Dec 12 21:52 bar
lrwxr-xr-x  1 aaa  staff  3 Dec 12 21:53 bar-soft -> bar

From here "lrwxr-xr-x ", we can see that bar-soft is a link file that points to bar.

$ ls -li
total 24
12895502721 -rw-r--r--  1 aaa  staff  4 Dec 12 21:52 bar
12895502801 lrwxr-xr-x  1 aaa  staff  3 Dec 12 21:53 bar-soft -> bar
12895502450 -rw-r--r--  2 aaa  staff  4 Dec 12 21:52 foo
12895502450 -rw-r--r--  2 aaa  staff  4 Dec 12 21:52 foo-hard

Foo and foo-hard have the same inode number (first column). This means that they are same file with different names. The third column 2 means that this file has 2 hard links.


Changing the name of foo does not matter:

$ mv foo foo-new
$ cat foo-hard
Cat

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

$ mv bar bar-new
$ ls bar-soft
bar-soft
$ cat bar-soft  
cat: bar-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.


Likewise, If foo is deleted, foo-hard still holds the contents; if bar is deleted, bar-soft is just a link to a non-existing file.


$ rm foo
$ ls -lrt
total 16
-rw-r--r--  1 tocao  staff  4 Dec 12 21:52 foo-hard
$ cat foo-hard
cat

After we remove foo, the hard link foo-hard is still there. The number of link (second column) is down to 1.


Related Post:

Hard Links and Symbolic Links In Linux

39 views

Join our mail group. Get a free Linux account on Cloud.

Never miss a post!

Want a free Linux account?  This account can be used to login to our cloud server and practice Linux commands.

 
kamateravps.gif
topbackgroud.png

✔ Linux Commands   ✔ Linux Skills    ✔ LinuxPerformance   ✔ Linux Interview

Some articles are from the public internet. If you find your article misused or undesired here and you don't want us to display it, please let us know and we'll remove it immediately.