理解硬链接和符号链接的区别
既然我们已经创建了硬链接和符号链接,现在让我们来比较它们的关键区别:
硬链接:
- 与原始文件共享相同的索引节点(inode)
- 不能链接到目录
- 不能跨文件系统边界
- 即使原始文件被删除或移动,仍然可以正常使用
- 对内容所做的更改会反映在所有硬链接中
符号链接:
- 有自己的索引节点,与目标文件不同
- 可以链接到目录
- 可以跨文件系统边界
- 如果目标文件被删除或移动,链接会失效
- 本质上是包含目标文件路径的指针文件
让我们通过示例来展示其中一些区别:
首先,让我们尝试为一个目录创建硬链接,这是不允许的:
mkdir testdir
ln testdir testdir_hardlink
你应该会看到类似这样的错误消息:
ln: testdir: hard link not allowed for directory
现在,让我们尝试为一个目录创建符号链接,这是允许的:
ln -s testdir testdir_symlink
让我们验证目录符号链接:
ls -la
你应该会在输出中看到 testdir_symlink -> testdir
,这表明 testdir_symlink
是指向 testdir
的符号链接。
我们可以在原始目录中创建一个文件:
echo "This is a test file in the directory." > testdir/testfile.txt
并通过符号链接访问它:
cat testdir_symlink/testfile.txt
你应该会看到以下内容:
This is a test file in the directory.
这表明符号链接可以指向目录并用于访问其内容。
另一个重要的区别是,删除原始文件会使符号链接失效,但不会影响硬链接。我们在符号链接的示例中已经看到了这一点。现在让我们用硬链接来演示:
rm original.txt
cat hardlink.txt
你仍然应该看到所有四行内容:
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.
硬链接仍然可以正常使用,因为数据仍然存在于磁盘上,并且硬链接仍然指向该数据。
然而,我们的符号链接现在已经失效了:
ls -l symlink.txt
cat symlink.txt
你应该会看到 symlink.txt
仍然存在,但它指向的文件已不存在,尝试读取它会产生错误。
让我们从硬链接重新创建原始文件:
cp hardlink.txt original.txt
cat symlink.txt
符号链接再次可用,因为它指向的文件又存在了。