Soft and Hard Links in Unix/Linux

A link in UNIX is a pointer to a file. Like pointers in any programming language, links in UNIX are pointers to files or directories. Creating a link is a shortcut to access a file. Links allow multiple filenames to refer to the same file elsewhere.

There are two types of links:

  1. soft link or symbolic link
  2. hard link

These links behave differently when their source (the content they link to) is moved or deleted. Symbolic links are not updated (they contain only a string, which is the pathname of their target); hard links always refer to the source, even if moved or deleted.

For example, if we have a file a.txt. If we create a hard link to a file and then delete the file, we can still access the file using the hard link. But if we create a soft link to a file and then delete the file, the file cannot be accessed through the soft link, and the soft link becomes dangling. Basically hard links increase the reference count of a location, while soft links are used as shortcuts (like in Windows)

1. Hard link

  • Each hard-linked file is assigned the same Inode value as the original file, so they refer to the same physical file location. Hard links are more flexible and remain linked even if the original or linked file is moved across the file system, although hard links cannot span different file systems.
  • The ls -l command displays all links, and the link column shows the number of links.
  • Links have actual file content
  • Removing any link will only reduce the number of links, but will not affect other links.
  • Hard links work fine even if we change the filename of the original file.
  • We cannot create hard links for directories to avoid recursive loops.
  • If the original file is deleted, the link still shows the contents of the file.
  • The size of any hard linked file is same as the original file, if we change the content in any hard link, the size of all hard linked files will be updated.
  • The disadvantage of hard links is that they cannot be created for files of different file systems, nor can they be created for special files or directories.
  • The command to create a hard link is:
$ ln [原始文件名] [链接名]

2. Soft link

  • 软链接类似于 Windows 操作系统中使用的文件快捷方式功能。每个软链接文件都包含一个指向原始文件的独立索引节点值。与硬链接类似,对任一文件中数据的任何更改都会反映在另一个文件中。软链接可以跨不同的文件系统链接,但是如果删除或移动了原始文件,软链接文件将无法正常工作(称为挂起链接)。
  • ls -l 命令显示第一列值为 l 的所有链接?链接指向原始文件。
  • 软链接包含原始文件的路径而不是内容。
  • 删除软链接除了删除原始文件外没有任何影响,链接变成“悬挂”链接,指向不存在的文件。
  • 软链接可以链接到目录。
  • 软链接的大小等于我们给的原文件的路径长度。例如,如果我们像 ln -s /tmp/hello.txt /tmp/link.txt这样链接一个文件,那么文件的大小将是 14 字节,等于“/tmp/hello.txt”的长度。
  • 如果我们更改原始文件的名称,那么该文件的所有软链接都会变得悬空,即它们现在毫无价值。
  • 跨文件系统链接:如果要跨文件系统链接文件,只能使用符号链接/软链接。
  • 创建软链接的命令是:
$ ln -s [原始文件名] [链接名]

本文由 mdnice 多平台发布

Guess you like

Origin blog.csdn.net/qq_35030548/article/details/130633481