What is a hard link? What is a symbolic link? How can create them? Why I do not know about this!
First of all. What is a link? You can see it like the connection between two things, if you are looking for the second one, the first one can lead you. In our case, link is the connection between two files
In this way, symbolic link is more easy to understand, because is an actual link to the original file, a direct link. In the other hand, a hard link is not a direct link to the original file, is more like a backup file of your original file, a mirror copy of the original file
How can we create them?
Well, there is a command to create them in our terminal in linux based operating systems, ln command. If we type the command line <man ln>, we can see the ln manual.
There are four forms for call ln command:
ln [OPTION]… [-T] TARGET LINK_NAME (1st form)
ln [OPTION]… TARGET (2nd form)
ln [OPTION]… TARGET… DIRECTORY (3rd form)
ln [OPTION]… -t DIRECTORY TARGET… (4th form)
In the 1st form, creates a link to TARGET with the name LINK_NAME. In the 2nd form, creates a link to TARGET in the current directory. In the 3rd and 4th forms, creates links to each TARGET in DIRECTORY. Without options, ln creates hard links by default.
Let’s make an example:
In the path ~/Documents/example/main we have a file called example.file which contains the text “This is an example”
Now, we want to create both, symbolic and hard link in the path ~/Documents/example/ , called symbolic_link and hard_link respectively, and which are linked with the example.file
For the first one, we use the command line
ln -s main/example symbolic_link
For the second one
ln main/example.file hard_link
Then, if we want to access to both files
Both links show the information contained in the example.file
But. What would happen if we delete the original file?
As I sad before, symbolic link is a direct link to the original file, if we delete the original file, we can’t access to its content anymore. In opposite, hard link is like a backup of the file and we can access to its content even if we delete the original file
Summarizing, a symbolic link
- can cross the file system
- allows us to link between directories
- has only the path of the original file, not the contents
A hard Link
- can’t cross the file system boundaries (i.e. A hardlink can only work on the same filesystem)
- can’t link directories
- permissions will be updated if we change the permissions of source file
- has the actual contents of original file, so that you still can view the contents, even if the original file moved or removed.