Hardlinks and Symlinks

In Unix environments there are two ways to link a file. The first being hard-linking. Hardlinking is different than symlinks in the fact that if you remove the original file that the hardlink points to, the link itself can still show you the content of the original file. Where as a symlink is useless without the original file (think “shortcuts” in Windows). Also, you cannot hardlink a directory, only symlink it. All this might seem hard to grasp, but let´s explain:

Hardlinks

A little experiment to show the case.

CODE
$ mkdir Test


( Making a new directory for our test )

CODE
$ cd Test


( Move in the directory )

CODE
$ vi fileA


( Make a file called fileA )

“i”
Type in some funny lines of text
< Esc >
ZZ ( save the file )

So, we made a ¨fileA¨ in a new directory called ¨Test¨ in your /home.

CODE
$ ln fileA fileB


( Making a hardlink )

CODE
$ ls -il fileA fileB


( The ¨i¨ argument will show the inode on the HD )
This is what you get:

QUOTE (Text @ Screen)
1482256 -rw-r–r– 2 bruno bruno 21 May 5 15:55 fileA
1482256 -rw-r–r– 2 bruno bruno 21 May 5 15:55 fileB

 

Here you can see that both fileA and fileB have the same inode number ( 1482256 ), also both files have the same file permissions and the same size, because that ´size´ is on the same inode it does not consume any extra space on your HD !

Now if we would remove the original ¨fileA¨

CODE
$ rm fileA


and have a look at the content of the ¨link¨ fileB

CODE
$ cat fileB

you will still be able to read the funny line of text you typed. ( MAGIC ! )

Symlinks

Staying in the same test directory as above we make a symlink:

CODE
$ ln -s fileB fileC
$ ls -il fileB fileC


This is what you´ll get:

QUOTE (Text @ Screen)
1482256 -rw-r–r– 1 bruno bruno 21 May 5 15:55 fileB
1482226 lrwxrwxrwx 1 bruno bruno 5 May 5 16:22 fileC -> fileB

 

You´ll notice the inodes are different and the link got a ¨l¨ before the rwxrwxrwx . The link has different permissions than the original file because it is just a symbolic link, its real content is just a string pointing to the original file. The size of the symlink ( 5 ) is the size of it´s string. ( The “-> fileB” at the end shows you where the link points to )

CODE
$ cat fileB


and

CODE
$ cat fileC


Will show the same funny text.

Now if we remove the original file:

CODE
$ rm fileB


and check the Test directory

CODE
$ ls


you will see the link fileC is still there, but if we do

CODE
$ cat fileC


it will tel you that there is no such file or directory !! Though

CODE
$ ls -il fileC


will still give you:

QUOTE (Text @ Screen)
1482226 lrwxrwxrwx 1 bruno bruno 5 May 5 16:22 fileC -> fileB

But the link is obsolete ! ( hope you´re still with me )

O.K. The test is over, you can delete the Test directory

Source 

No Posts Found

Tags: ,

Leave a Reply

You must be logged in to post a comment.