Hard and Soft Links | LinuxGist
This article will provide details on how we can create hard and soft links in Linux.
Introduction
In Linux, hard links and soft (symbolic) links are two types of file system pointers that allow you to refer to the same data using different names.
Hard Links
Definition: A hard link is a reference to an inode (file system entry) in the filesystem. An inode contains all the metadata about a file, including its permissions, ownership, and contents.
- Use Cases:
- When you want to have multiple names for the same file without duplicating data.
- To ensure that deleting one name of the file does not delete the actual data until all links are removed.
- Creating a Hard Link:
1
ln original_file hard_link_name
For example, if you have a file named
foo.txt
and you want to create a hard linkbar.txt
that points to it:1 2 3
touch foo.txt ln foo.txt bar.txt ls -i
Both shares the same inode as the target file.
1
5637698 bar.txt 5637698 foo.txt
Soft (Symbolic) Links
Definition: A soft link (symbolic link) is a special type of file that contains the path to another file or directory. It can span across different filesystems and even different partitions.
- Use Cases:
- When you need to create a reference to a file or directory in a different location.
- To provide an alias for long paths.
- To link to files on other filesystems without needing to mount them.
- Creating a Soft Link:
1
ln -s target_file_or_directory soft_link_name
For example, if you have a file named
foo.txt
in the/home/user/documents
directory and you want to create a symbolic linkbar.txt
that points to it:1
ln -s /home/<user>/documents/foo.txt bar.txt
Key Differences
- Hard Link:
- Points directly to an inode.
- Can span across filesystems (but usually within the same partition).
- Cannot link to a non-existent file or directory.
- Removing the original file leaves the hard link intact, and vice versa.
- Soft Link:
- Points to another path in the filesystem (file or directory).
- Can span across different filesystems.
- Can point to a non-existent target (the link will be broken if the target is deleted).
- Removing the original file or directory does not affect the soft link.
Examples
- Hard Link Example:
1 2 3 4 5 6
# Create a hard link ln /home/user/documents/foo.txt /home/user/backup/foo.txt # List files to see the hard link ls -l /home/user/documents ls -l /home/user/backup
- Soft Link Example:
1 2 3 4 5 6
# Create a soft link ln -s /home/user/documents/foo.txt /home/user/backup/foo_link # List files to see the soft link ls -l /home/user/documents ls -l /home/user/backup
Conclusion
In summary, hard links provide a way to have multiple names for the same file without duplicating data, while soft links allow you to create references to files or directories in different locations, including spanning filesystems.