Hardlink and softlink in linux

Символические и жесткие ссылки Linux

Символические и жесткие ссылки — это особенность файловой системы Linux, которая позволяет размещать один и тот же файл в нескольких директориях. Это очень похоже на ярлыки в Windows, так как файл на самом деле остается там же где и был, но вы можете на него сослаться из любого другого места.

В Linux существует два типа ссылок на файлы. Это символические и жесткие ссылки Linux. Они очень сильно отличаются и каждый тип имеет очень важное значение. В этой небольшой статье мы рассмотрим чем же отличаются эти ссылки, зачем они нужны, а также как создавать ссылки на файлы в Linux.

Символические ссылки

Символические ссылки более всего похожи на обычные ярлыки. Они содержат адрес нужного файла в вашей файловой системе. Когда вы пытаетесь открыть такую ссылку, то открывается целевой файл или папка. Главное ее отличие от жестких ссылок в том, что при удалении целевого файла ссылка останется, но она будет указывать в никуда, поскольку файла на самом деле больше нет.

Вот основные особенности символических ссылок:

  • Могут ссылаться на файлы и каталоги;
  • После удаления, перемещения или переименования файла становятся недействительными;
  • Права доступа и номер inode отличаются от исходного файла;
  • При изменении прав доступа для исходного файла, права на ссылку останутся неизменными;
  • Можно ссылаться на другие разделы диска;
  • Содержат только имя файла, а не его содержимое.

Теперь давайте рассмотрим жесткие ссылки.

Жесткие ссылки

Этот тип ссылок реализован на более низком уровне файловой системы. Файл размещен только в определенном месте жесткого диска. Но на это место могут ссылаться несколько ссылок из файловой системы. Каждая из ссылок — это отдельный файл, но ведут они к одному участку жесткого диска. Файл можно перемещать между каталогами, и все ссылки останутся рабочими, поскольку для них неважно имя. Рассмотрим особенности:

  • Работают только в пределах одной файловой системы;
  • Нельзя ссылаться на каталоги;
  • Имеют ту же информацию inode и набор разрешений что и у исходного файла;
  • Разрешения на ссылку изменяться при изменении разрешений файла;
  • Можно перемещать и переименовывать и даже удалять файл без вреда ссылке.

Использование ссылок в Linux

Теоретические отличия вы знаете, но осталось закрепить все это на практике, поэтому давайте приведем несколько примеров работы со ссылками в Linux. Для создания символических ссылок существует утилита ln. Ее синтаксис очень прост:

$ ln опции файл_источник файл_ссылки

  • -d — разрешить создавать жесткие ссылки для директорий суперпользователю;
  • -f — удалять существующие ссылки;
  • -i — спрашивать нужно ли удалять существующие ссылки;
  • -P — создать жесткую ссылку;
  • -r — создать символическую ссылку с относительным путем к файлу;
  • -s — создать символическую ссылку.

Создание символических ссылок

Сначала создайте папку test и перейдите в нее:

Затем создайте файл с именем source с каким-либо текстом:

echo «текст текст текст текст» > source
$ cat source

Файл готов, дальше создадим символическую ссылку Linux, для этого используется команда ln с опцией -s:

Попробуем посмотреть содержимое файла по ссылке:

Читайте также:  Linux macbook pro 2019

Как видите, нет никакой разницы между ней и исходным файлом. Но утилита ls покажет что это действительно ссылка:

Несмотря на то, что содержимое одинаковое, здесь мы видим, что адрес иноды и права доступа к файлам отличаются, кроме того, явно показано что это символическая ссылка Linux.

Теперь удалите исходный файл и посмотрите что будет:

Вы получите ошибку, что такого файла не существует, потому что мы действительно удалили исходный файл. Если вы удалите ссылку, то исходный файл останется на месте.

Создание жестких ссылок

Снова создайте файл source с произвольным текстом:

echo «текст текст текст текст» > source
$ cat source

Теперь создадим жесткую ссылку Linux. Для этого достаточно вызвать утилиту без параметров:

Посмотрите содержимое файла:

Данные те же самые, а если мы посмотрим вывод утилиты ls, то увидим что inode и права доступа тоже совпадают:

Если для одного из файлов поменять разрешения, то они изменяться и у другого. Теперь удалите исходный файл:

Затем посмотрите содержимое:

Как видите, ничего не произошло и ссылка по-прежнему указывает на нужный участок диска, это главное отличие жесткой ссылки от символической. Мы можем сделать вывод, что жесткая ссылка linux это обычный файл. Каждый файл имеет как минимум одну ссылку, но для некоторых мы можем создать несколько ссылок.

Выводы

Это все, что вам было необходимо знать про символические и жесткие ссылки linux. Надеюсь, вы получили общее представление об этих возможностях файловой системы и сможете использовать их для решения своих задач.

На завершение видео про ссылки в Linux:

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

Hard links and soft links explained

Have you ever been familiar with something, worked around it, but not fully understood its concepts? I feel like that happens to me more than most people. This is a frustrating feeling, but it is also one that often is easily remedied. Sometimes, it only takes someone explaining the concept in «plain English,» aka layman’s terms. That is the goal of this article. I want to talk about hard links and soft (symbolic) links in the most basic terms possible. You may realize that this concept, which is often a struggle for sysadmins, is quite simple. If nothing else, I take you through the syntax to create these links (which many people find difficult to remember). So let’s get down to it.

The concept of a hard link is the most basic we will discuss today. Every file on the Linux filesystem starts with a single hard link. The link is between the filename and the actual data stored on the filesystem. Creating an additional hard link to a file means a few different things. Let’s discuss these.

First, you create a new filename pointing to the exact same data as the old filename. This means that the two filenames, though different, point to identical data. For example, if I create file /home/tcarrigan/demo/link_test and write hello world in the file, I have a single hard link between the file name link_test and the file content hello world.

[tcarrigan@server demo]$ ls -l total 4 -rw-rw-r--. 1 tcarrigan tcarrigan 12 Aug 29 14:27 link_test

Take note of the link count here (1).

Next, I create a new hard link in /tmp to the exact same file using the following command:

[tcarrigan@server demo]$ ln link_test /tmp/link_new

The syntax is ln (original file path) (new file path) .

Читайте также:  Linux notify send the

Now when I look at my filesystem, I see both hard links.

[tcarrigan@server demo]$ ls -l link_test /tmp/link_new -rw-rw-r--. 2 tcarrigan tcarrigan 12 Aug 29 14:27 link_test -rw-rw-r--. 2 tcarrigan tcarrigan 12 Aug 29 14:27 /tmp/link_new

The primary difference here is the filename. The link count has also been changed (2). Most notably, if I cat the new file’s contents, it displays the original data.

[tcarrigan@server demo]$ cat /tmp/link_new hello world

When changes are made to one filename, the other reflects those changes. The permissions, link count, ownership, timestamps, and file content are the exact same. If the original file is deleted, the data still exists under the secondary hard link. The data is only removed from your drive when all links to the data have been removed. If you find two files with identical properties but are unsure if they are hard-linked, use the ls -i command to view the inode number. Files that are hard-linked together share the same inode number.

[tcarrigan@server demo]$ ls -li link_test /tmp/link_new 2730074 -rw-rw-r--. 2 tcarrigan tcarrigan 12 Aug 29 14:27 link_test 2730074 -rw-rw-r--. 2 tcarrigan tcarrigan 12 Aug 29 14:27 /tmp/link_new

The shared inode number is 2730074, meaning these files are identical data.

If you want more information on inodes, read my full article here.

Hard limits

While useful, there are some limitations to what hard links can do. For starters, they can only be created for regular files (not directories or special files). Also, a hard link cannot span multiple filesystems. They only work when the new hard link exists on the same filesystem as the original.

Commonly referred to as symbolic links, soft links link together non-regular and regular files. They can also span multiple filesystems. By definition, a soft link is not a standard file, but a special file that points to an existing file. Let’s look at how to create a soft link. I use the ln -s command and the following syntax:

ln -s (file path you want to point to) (new file path)

In the example below, I create a new file at /home/tcarrigan/demo/soft_link_test with the file content soft Hello world. I then create a soft link to that file at /tmp/soft_link_new :

[tcarrigan@server demo]$ ln -s /home/tcarrigan/demo/soft_link_test /tmp/soft_link_new [tcarrigan@server demo]$ ls -l soft_link_test /tmp/soft_link_new -rw-rw-r--. 1 tcarrigan tcarrigan 17 Aug 30 11:59 soft_link_test lrwxrwxrwx. 1 tcarrigan tcarrigan 35 Aug 30 12:09 /tmp/soft_link_new -> /home/tcarrigan/demo/soft_link_test

Notice that /tmp/soft_link_new is just a symbolic link, pointing to the original /home/tcarrigan/demo/soft_link_test . If I cat the content of /tmp/soft_link_new , I should see the soft Hello world text.

[tcarrigan@server demo]$ cat /tmp/soft_link_new soft Hello world

All of this sounds great, but there are some drawbacks to using a soft link. The biggest concern is data loss and data confusion. If the original file is deleted, the soft link is broken. This situation is referred to as a dangling soft link. If you were to create a new file with the same name as the original, your dangling soft link is no longer dangling at all. It points to the new file created, whether this was your intention or not, so be sure to keep this in mind.

Hard or soft?

There is no clear answer here. The best link is the type that fits your particular situation. While these concepts can be tricky to remember, the syntax is pretty straightforward, so that is a plus! To keep the two easily separated in your mind, I leave you with this:

  • A hard link always points a filename to data on a storage device.
  • A soft link always points a filename to another filename, which then points to information on a storage device.
Читайте также:  Login screen kali linux

Hopefully, this helps you keep them separated as you work your way through the link types needed to accomplish your daily goals!

Источник

Hardlink and Softlink in Linux

Hard links and softlinks are two different types of links that are very useful on Linux. Here, let’s discuss them with examples.

Hard link shares the same inodes as the original file. It is the mirror copy of the original file. It is only useful for files as it cannot create links for directories. If you change the content to either original or hard link file then changes occur on both. The main fact about hard link is that they do not get deleted even by deleting the original file.

Soft link is also known as symbolic link. It does not share the same inode as the original file. It is the definite link to the original file so if you remove the original file then it also gets removed. It can create links for both files and directories.

Hard Link Soft Link
Even if the original file gets deleted, it does not get deleted. If the original file gets deleted, then it will also get deleted.
Shares same inode number Shares different inode number
Mirror copy of the original file Definite link to the original file
Can link only files Can link both files and directories

Let’s create a file named linuxways.txt and create a hard link to this file.

$ sudo ln linuxways.txt hardlinktest.txt

Inode numbers for both hardlinktest.txt and linuxways.txt are the same i.e 393248 and same file permissions (-rw-r–r–). Hard link file does not get deleted even if the original file gets deleted.

Hard Link file still exists with the same content.

It proves a hard link file does not get deleted even after deleting the original file. If the hard link file needs to be deleted then you must delete it with the following command:

Let’s create a file named linuxways.txt and create a soft link to this file.

$ sudo ln -s linuxways.txt softlinktest.txt

Here, inode numbers are different for the original and soft link file, also you can see different file permissions. If you delete the original file then the soft link file also gets deleted as it is the actual copy of the original file.

Conclusion:

This is the way you create hard links and soft links also known as symbolic links. You must get the basic difference between them and the process of creating such links now. Thank you!

Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications including CCNA RS, SCP, and ACE. As an IT engineer and technical author, he writes for various websites.

Источник

Оцените статью
Adblock
detector