Hard Links
By using Hard link we can create an alias for an existing file. Now this file can be accessed by any of the two names, i.e. either by alias or by its original name. Suppose, I create a file "Hello" as following
[code]cat>Hello
echo Hello World
[/code]
Now assign executable permission to this file
[code]chmod u+x Hello[/code]
Now run the file using
[code]./Hello[/code]
And the output will be
Hello World
Now check the details of this file using
[code]ls -l Hello[/code]
-rwxr- -r- - 1 user1 user1 0 2012-04-12 17:58 Hello
Just examine the number 1 after file permission column. This number tells the number of links a file has. At this point its value is 1 wich means that the file can be accessed by only one name i.e. "Hello".
Now, when we create the Hard link for a file, we actually create an alias for a file. When we create a Hard link for a file then it can be accessed by more than one name, but actually it is present at only one space in Hard disk. This means with the help of Hard link more than one name can point to the actual file. We make changes to the file using any name, and those changes are reflected in the actual file. Next time when we access the file using some other name, our changes can be seen in the file
Now we will see it with the help of example
To create a Hard link for file Hello write following command on shell.
[code]ln Hello Hi[/code]
Now run the following command
[code]ls -l Hello[/code]
And the output will be
-rwxr- -r- - 2 user1 user1 0 2012-04-12 17:58 Hello
Note: Link number has changed to 2.
This was because alias "Hi" also links to the same file.
In order to confirm that both are same files, type the following command
[code]ls -li Hello Hi[/code]
The output will be
4882474 -rwxr- -r- - 2 user1 user1 0 2012-04-12 17:58 Hello
4882474 -rwxr- -r- - 2 user1 user1 0 2012-04-12 17:58 Hi
Note: inode numbers for both the outputs are same. This means there is only one file physically, or in directory system.
Now we can access this file using any of the aliases.
ls -l Hello or ls -l Hi both are same
Now when we execute remove command on Hello
[code]rm Hello [/code]
After that execute ls -l Hi. Output will be
4882474 -rwxr- -r- - 1 user1 user1 0 2012-04-12 17:58 Hi
Note: File is not deleted physically, only the alias Hello, which was earlier pointing to the file, was removed. Our data is still conserved in the file and can be accessed using alias "Hi".
Why do we use Hard links? What are the advantages of using Hard links?
i) Hard links provide protection against accidental deletions. Actually this has been shown above, even after we deleted alias "Hello", we could access the file using alias "Hi".
ii) Suppose we have some programs which expect a file in their directory. Now, we moved that file from that directory to some other directory. So, instead of changing path of the file in individual programs we can just make a hard link of that file in programs' directory.
For more information visit
No comments:
Post a Comment