更新
本文章更新于 2017.11.12,如果本节更新内容与下面小节的内容不一致,以这个小节为准。
As the saying goes, a picture is worth a thousand words. Here is how I visualize it:
If you don’t know what inode is, please refer to wikipedia page about it. The picture above tells us a hard link just creates another file with a link to the same underlying inode. Therefore, if you want to delete the inode, then you have to delete all the links to it. For a soft link, if you delete or rename myfile.txt
will invalidate it and cause it can’t find inode. Let me show you an example. You will understand it deeply.
I created a directory named lnte
in my Ubuntu os and printed its apparent sizes in byte by typing following command:
du -b lnte
And you would see that it take up 4096 bytes. As shown in the picture below, you may find that a hard link doesn’t occupy any space on disk whereas a soft link indeed consumes 5-bytes space.
软链接
首先,我在我的target目录下创建了文件lovedog.txt,并写了一行文字,如下图:
接着,我在target的父目录shelltest中创建一个指向lovedog.txt的符号链接,即软链接,并编辑了一下。如下图:
当我们去target目录中看lovedog.txt文件时,内容也发生了变化。同样的道理,我可以创建很多个软链接指向lovedog.txt,如下图:
同样,当我们修改任何一个软链接文件都会使内容发生改变,文件都保持同步变化。我们也可以看到软链接只有18Kb并不会占用磁盘空间。它只是一个原文件的引用,当我们将原文件删除以后,引用将会失效。
硬链接
我们可以通过下图的命令来创建硬链接:
从上面2幅图我们可以看出硬链接的大小和原文件一样,并且索引节点号也一样。当我们改变硬链接的文件内容时,同样也会改变原文件的内容。
如上图所示,当我们删除原文件,软链接已经失效,而硬链接依然拥有原文件的数据。
当我们用cp命令复制软链接时,我们复制的是原文件,而不是一个软链接。所以下图所示的backup和原文件和大小相同。但是,当我们修改backup时,并不会修改原文件和内容。