Soft link and Hard link in Linux/UNIX
What is a link?
Links are pointers pointing to a file or directory. A link is a shortcut to access a file, similar to a Windows shortcut.
Soft Link
In soft links, we can create links on files and directories. Links enable the creation of references to files and directories.
syntax: ln -s <original-file-path> <link-file-path>
Soft links can be created in any filesystem.
In soft link, the original file and soft link file have different inode values.
We cannot access the data from the soft link file after removing the original file, because the soft link does not have access to any memory.
Creating a soft link:
Here, we created a file named sample.txt and added some contents inside the file.
Now we creating a soft link to the sample.txt file using the ln
command with -s
flag referring to soft link. To check the inode value use -i
flag with ls
command. Note the inode values are different for the original file and the soft link file we created.
# creating a soft link
ln -s sample.txt sl_sample.txt
If we make any changes to the original file then the changes will automatically apply to the linked file.
If we delete the original file then the data present in the linked file will be lost automatically. This is because the linked file always points to the original file and the soft link does not access the memory.
Hard Link
The hard link points to the same inode similar to the original file, which means both the original file and the linked file have the same inode value.
syntax: ln <original-file> <linked-file>
Hard link should be created in the same filesystem, unlike soft link.
We can access the data from the hard link file after removing the original file because the hard link has memory access.
Creating a hard link:
Here, we created a file named sample.txt and added some contents inside the file.
Now we creating a hard link to the sample.txt file using the ln
command. To check the inode value use -i
flag with ls
command. Note the inode values are the same for the original file and the hard link file we created.
If we delete the original file then the data present in the linked file will not be lost. This is because the linked file always points to the inode and the hard link has access to memory. Inodes store information about the file metadata and data block locations.
Thank you.