Understanding the Differences Between Hard and Symbolic Links
Now that we have created both hard and symbolic links, let's compare their key differences:
Hard Links:
- Share the same inode as the original file
- Cannot link to directories
- Cannot cross file system boundaries
- Continue to work even if the original file is deleted or moved
- Changes to the content are reflected in all hard links
Symbolic Links:
- Have their own inode, different from the target file
- Can link to directories
- Can cross file system boundaries
- Become broken if the target file is deleted or moved
- Are essentially pointer files that contain the path to the target
Let's demonstrate some of these differences with examples:
First, let's try to create a hard link to a directory, which is not allowed:
mkdir testdir
ln testdir testdir_hardlink
You should see an error message like:
ln: testdir: hard link not allowed for directory
Now, let's try to create a symbolic link to a directory, which is allowed:
ln -s testdir testdir_symlink
Let's verify our directory symbolic link:
ls -la
You should see testdir_symlink -> testdir
in the output, indicating that testdir_symlink
is a symbolic link to testdir
.
We can create a file inside the original directory:
echo "This is a test file in the directory." > testdir/testfile.txt
And access it through the symbolic link:
cat testdir_symlink/testfile.txt
You should see the content:
This is a test file in the directory.
This demonstrates that symbolic links can point to directories and be used to access their contents.
Another important difference is that deleting the original file breaks a symbolic link but not a hard link. We've already seen this with our symbolic link example. Let's demonstrate this with our hard link:
rm original.txt
cat hardlink.txt
You should still see all four lines:
This is the original file for our link examples.
This is an added line.
Another line added through the hard link.
This line was added through the symbolic link.
The hard link continues to work because the data still exists on disk, and the hard link still points to that data.
However, our symbolic link is now broken:
ls -l symlink.txt
cat symlink.txt
You should see that symlink.txt
still exists but points to a file that no longer exists, and trying to read it produces an error.
Let's recreate the original file from our hard link:
cp hardlink.txt original.txt
cat symlink.txt
The symbolic link works again because the file it points to exists once more.