Linux Soft Link and Hard Link
In Linux, links are used to create shortcuts or references to files. There are two types of links:
- Soft Link (Symbolic Link): A shortcut that points to the original file.
- Hard Link: A direct reference to the data of the original file.
Soft Link
A soft link is similar to a shortcut in Windows. It points to the original file and can span across different file systems.
Command to create a soft link:
ln -s target_file link_name
Example:
ln -s /home/user/file.txt /home/user/softlink.txt
This creates a symbolic link softlink.txt pointing to file.txt.
Hard Link
A hard link is another name for the same file. It shares the same inode as the original file and cannot span across different file systems.
Command to create a hard link:
ln target_file link_name
Example:
ln /home/user/file.txt /home/user/hardlink.txt
This creates a hard link hardlink.txt that points to the same data as file.txt.
Viewing Links
To view the links associated with a file, you can use the ls -l command. The output will show the link count and the type of link.
ls -l
The output will look something like this:
lrwxrwxrwx 1 user user 20 Oct 10 14:30 softlink.txt -> /home/user/file.txt
In this example, softlink.txt is a symbolic link pointing to /home/user/file.txt.
For hard links, the output will look like this:
-rw-r--r-- 2 user user 1024 Oct 10 14:30 hardlink.txt
In this case, the number 2 indicates that there are two hard links to the same file.
Deleting Links
To delete a soft link, use the rm command:
rm softlink.txt
To delete a hard link, use the same command:
rm hardlink.txt
Note that deleting a hard link does not delete the original file unless all hard links are removed.
Limitations
Soft links can point to files or directories, while hard links can only point to files. Additionally, hard links cannot be created for directories in most file systems.
When using hard links, be cautious as deleting the original file does not delete the data if there are other hard links pointing to it.
Use Cases
Soft links are useful for creating shortcuts to files or directories, while hard links are useful for creating multiple references to the same data without duplicating it.
Unlink command
The unlink command is used to remove a single file. It can be used for both soft and hard links.
Command:
unlink link_name
Example:
unlink /home/user/softlink.txt
Key Differences
| Feature | Soft Link | Hard Link |
|---|---|---|
| File System | Can span across file systems | Cannot span across file systems |
| Inode | Different inode from the original file | Shares the same inode as the original file |
| Original File Deletion | Link breaks if the original file is deleted | Link remains functional even if the original file is deleted |
Use the appropriate link type based on your requirements. Soft links are useful for creating shortcuts, while hard links are useful for creating multiple references to the same data.