最近我在一次工作面试中被问到这个问题。我诚实地说,我知道符号链接的行为和如何创建一个,但不了解硬链接的使用,以及它与符号链接的区别。


当前回答

在进行增量备份时,硬链接非常有用。例如,请参阅rsnapshot。这个想法是使用硬链接进行复制:

拷贝备份号n到n + 1 拷贝备份n - 1到n ... 拷贝备份0到备份1 用任何更改过的文件更新备份0。

除了您所做的任何更改之外,新的备份不会占用任何额外的空间,因为所有增量备份都将指向未更改的文件的同一组inode。

其他回答

俗话说,一幅画胜过千言万语。以下是我对它的想象:

下面是我们如何得到这张照片的:

Create a name myfile.txt in the file system that points to a new inode (which contains the metadata for the file and points to the blocks of data that contain its contents, i.e. the text "Hello, World!": $ echo 'Hello, World!' > myfile.txt Create a hard link my-hard-link to the file myfile.txt, which means "create a file that should point to the same inode that myfile.txt points to": $ ln myfile.txt my-hard-link Create a soft link my-soft-link to the file myfile.txt, which means "create a file that should point to the file myfile.txt": $ ln -s myfile.txt my-soft-link

看看如果myfile.txt被删除(或移动)会发生什么:my-hard-link仍然指向相同的内容,因此不受影响,而my-soft-link现在什么都不指向。其他答案讨论了每种方法的利与弊。

What you think of as an ordinary "file" is actually two separate things: The data of a file, and a directory entry. When you create a hard link for a file, you actually create a second directory entry which refers to the same data. Both directory entries have the exact same functionality; each one can be used to open the file to read it. So you don't really have "a file plus a hard link", you have "file data with two directory entries". What you think of as deleting a file actually deletes a directory entry, and when the last directory entry for the data is deleted, then the data itself is deleted as well. For ordinary files that have only one directory entry, deleting the directory entry will delete the data as always. (While a file is opened, the OS creates a temporary link to the file, so even when you delete all directory entries, the data stays but disappears as soon as you close the file).

例如,创建文件a .txt,硬链接B.txt,然后删除a .txt。当您创建a .txt时,会创建一些数据,并创建一个目录条目a .txt。在创建硬链接时,创建了另一个目录条目B.txt,指向完全相同的数据。当您删除a .txt时,您仍然拥有所有数据和一个目录条目B.txt,就像您首先创建了一个文件B.txt一样。

软链接只是一个(几乎)普通的文件,只是它不包含数据,而是另一个目录条目的路径。如果你删除了软链接所指向的文件,那么软链接将包含一个不再指向目录条目的路径;它坏了。如果你删除软链接,就像删除任何其他文件一样,它指向的文件不受影响。

我推荐你们去维基百科:

符号链接 硬链接

以下几点:

与硬链接不同,符号链接可以跨文件系统(大多数情况下)。 符号链接可以指向目录。 硬链接指向一个文件,并允许您使用多个名称引用同一个文件。 只要至少有一个链接,数据就仍然可用。

符号链接为文件提供了另一个名称,在某种程度上类似于硬链接。但是,即使文件中仍然存在符号链接,也可以删除文件。

我对使用的两点看法:

软链接可以用来缩短长路径名,例如:

ln -s /long/folder/name/on/long/path/file.txt /short/file.txt

对/short/file.txt所做的更改将应用于原始文件。

硬链接可以用来移动大文件:

$ ls -lh /myapp/dev/
total 10G
-rw-r--r-- 2 root root 10G May 22 12:09 application.bin

ln /myapp/dev/application.bin /myapp/prd/application.bin

即时复制到不同的文件夹,原始文件(在/myapp/dev上)可以移动或删除,而不会触及/myapp/prd上的文件