Linux Create Hard Links and Soft Links (Symbolic)
We are going to show you how to create hard links and soft links. To create a soft link just use the “-s” parameter. Otherwise it will just be a hardlink.
To create a hard link you can use the following command:
ln sourceFile.txt linkToFile.txt
To create a soft link you can use the following command:
ln -s sourceFile.txt linkToFile.txt
Soft links can be specified using either relative or absolute path. Using a relative path can be useful if both the link and the original file are within the same directory and that directory might be moved or changed.
ln -s /home/user1/test1.sh current.sh ln -s ../../test1.sh current.sh
Absolute paths are useful if you want to move the link but don’t want to move the original file.
Difference Between Soft and Hard Links
Soft links are not the same as hard links. Knowing the difference is important.
What is a Soft Link?
A soft link is also referred to as a symbolic link.
A soft link is just a pointer to a filename. The actual file name points to the data on disk.
- Removing a soft link will not delete the original file.
- Removing the original file will not delete the soft link but will result in a broken link that points to nothing.
What is a Hard Link?
Creating a hard link basically just creates another name for the same data on disk. A file name is just a name that points to some data on a disk. It is probably easier to think of it as an alternate name or alternate directory entry and not just a link.
A hard link is basically the same thing as the original name for a file.
Deleting the original file will not actually delete the file if it still has hard links pointing to it. To delete a file all hard links to the file need to be deleted.
Find and Delete All Hard Links
You show the number of hard links that a file has with the ls command. The second column will show you the number of links.
ls -l test1.sh
You can find all hard links to a file like this:
find /home -xdev -samefile test1.txt
You can delete them all ( including the original ) like this:
find /home -xdev -samefile test1.txt | xargs rm