Hard and Soft Filesystem Links
Hard and Soft Filesystem Links
In Linux, it's possible to create links to files and directories. Links are pointers to a file or directory that can be used to access the original content without having to navigate to its physical location in the filesystem.
There are two types of links in Linux: hard links and soft links (also called symbolic links).
Hard Links
A hard link is a direct link to a file that points to the same inode as the original file. Inodes are data structures that hold information about a file, such as its permissions, ownership, and timestamps. Because a hard link points directly to the inode, all hard links to a file are essentially equivalent; there is no "original" file and no "copy".
Creating a hard link to a file is done with the ln
command, followed by the name of the file and the desired link name. For example, to create a hard link to a file called file1
with the name link1
, we would use the following command:
ln file1 link1
Note that creating a hard link to a directory is not allowed, as it can cause issues with the filesystem hierarchy.
Soft Links
A soft link, or symbolic link, is a special type of file that acts as a pointer to another file or directory. Unlike hard links, soft links are separate files that reference the original file by its path. Soft links can point to files or directories on different filesystems or even on different machines, as long as the path is correct.
Creating a soft link is done with the ln
command using the -s
option, followed by the name of the file or directory and the desired link name. For example, to create a soft link to a file called file1
with the name link1
, we would use the following command:
ln -s file1 link1
When working with soft links, it's important to note that they can become broken if the original file or directory is moved or deleted. In this case, the soft link will still exist but will no longer point to a valid location.
Checking Links
To check if a file is a link and if it's a hard or soft link, you can use the ls
command with the -l
option, which displays detailed information about a file. The first character in the output indicates the type of the file, and the number after it indicates the number of hard links to the file.
For example, to check if link1
is a hard or soft link, we can use the following command:
ls -l link1
The output will show something like this:
lrwxr-xr-x 1 user group 5 Mar 25 14:25 link1 -> file1
In this example, the first character in the output is an "l", which indicates that it's a soft link. The arrow symbol "->" shows the path to the original file.