In Windows we often use shortcuts to create links that are easy to use on our computers. In Linux, there are two ways to create links, soft links and hard links. Let’s talk about the difference in detail.

define

Ln (short for Link File) is a basic tool in the GNU Core Toolkit. This command creates a synchronous link for a file in another location. If you need to use the same file in different directories, you do not need to put the same file in each directory. In this case, you only need to use ln to create the link of the corresponding file, and do not need to occupy disk space repeatedly.

The command format

# hard link (source can only be file)
ln source target
# soft link (source can be file or directory)
ln -s source target
Copy the code

Soft links

The soft link symbolic Link is equivalent to the shortcut in Windows. Its contents point to the location of another file. So you can create a soft link to a directory, or you can link to a file that doesn’t exist. In addition, it can cross file systems. None of these three hard links will work.

Hard links

A hard link can be interpreted as an alias for a file, and there can be multiple aliases.

The principle of

For Linux, the file structure is somewhat similar to that of Windows, consisting of the file name, inode (similar to the FCB file control block on Windows, which holds some information about the file), and data. For example, if you create an Origin file, you will get the following information.

Note inodes and hard links, and create hardlink for Origin.

By comparison, it is found that the file hardlink is identical to the original file Origin except for its name, just as the same person has a formal name and may also have a nickname. They obviously have exactly the same data.

Next, we create origin’s softlink, softlink.

The comparison shows that Origin and SoftLink are completely different files with different sizes, blocks, inodes and types. The only connection is that the SoftLink file points to the Origin file (which smacks of a file pointer).

Use cases

Impact of deleting source files on soft and hard links

As can be seen from the figure above, the number of hard links in HardLink is one less, while SoftLink still exists unharmed. Next we open the file through two links.

As shown above, Hardlink can still open the file, while soft link cannot view the original file.

reference

  1. GUN Core Toolkit
  2. Wikipedia ln
  3. Ln the source code

If this article is helpful to you, or you are interested in technical articles, you can follow the wechat official number: Technical Tea Party, and you can receive relevant technical articles in the first time. Thank you!

This article was automatically published by ArtiPub