- Жесткие и Символьные ссылки в Linux
- Жесткая ссылка (Hard link)
- Символьная ссылка (Symbolic link)
- Жесткие ссылки vs. Символьные ссылки
- Удаление ссылок
- Заключение
- How to create a hard links in Linux or Unix
- How to create a hard links in Linux or Unix
- ln command example to make a hard link on a Linux
- ln Command Syntax T Create Hard Link in Linux
- How do I delete a hard link on Linux or Unix?
- Hard Links Limitations on Linux and Unix
- Everything Important You Need to Know About Hard Link in Linux
- What is hard link in Linux?
- How to create hard links in Linux
- Things to keep in mind about hard links
- Deleting the target file won’t delete its data anymore if it has hard link
- You should not create a hard link to a directory
- It’s nearly impossible to distinguish between the hard links and the original file
- Bonus Tip: How to find all hard links to a given file
Жесткие и Символьные ссылки в Linux
Обновл. 14 Май 2021 |
Ссылка в Unix-подобных системах — это своего рода указатель, напоминающий указатели в языках программирования, с той лишь разницей, что он указывает на файл или каталог. Ссылки позволяют нескольким именам файлов ссылаться на один и тот же файл, расположенный где-то в другом месте. В Linux-системах существуют два разных типа ссылок: символьная (или «мягкая», «символическая») ссылка и жесткая ссылка. На этом уроке мы разберем, чем символьная ссылка отличается от жесткой, и как с ними работать.
Жесткая ссылка (Hard link)
Предположим, вы захотели скопировать файл. В процессе копирования будет создан новый файл. Его непосредственные данные запишутся в свободное место на диске, а самому файлу система назначит уникальный идентификатор — индексный номер (сокр. «inode» от англ. «index node«).
Создавая жесткую ссылку (англ. «hard link») на файл, мы привязываемся к его индексному номеру, получая тот же самый файл (с новым именем), на который указывает ссылка, но без физического создании копии.
Для создания жесткой ссылки используется команда ln (от англ. «link»), имеющая довольно простой синтаксис:
$ ln целевой_файл имя_ссылки
Для примера создадим ссылку с именем hardlink1, указывающую на уже существующий файл file1:
$ ln file1 hardlink1
Чтобы убедиться, что файл file1 и ссылка hardlink1, по сути, являются одним и тем же объектом файловой системы — сравним их индексные номера, выполнив команду ls вместе с опциями -l (отображать расширенную информацию), -i (выводить inode) и -h (использовать буквы для обозначения размера):
Как можно заметить, file1 и hardlink1 имеют общий индексный номер — 131094 . Теперь давайте создадим еще одну ссылку и посмотрим, как поведет себя счетчик ссылок (число, следующее за группой установленных разрешений файла):
$ ln file1 hardlink2
$ ls –lih
Обратите внимание, теперь счетчик ссылок показывает цифру 3 вместо 2.
Символьная ссылка (Symbolic link)
Символьная ссылка (сокр. «symlink» от англ «symbolic link«), в отличие от жесткой ссылки, указывает не на индексный номер файла, а на его имя (путь). В каком-то роде символьная ссылка является аналогом ярлыка в Windows-системах.
Символьную ссылку можно создать с помощью той же команды ln , добавив к ней опцию -s :
$ ln -s file1 symlink1
При этом будет создан новый (!) объект файловой системы с именем symlink1, указывающий на существующий файл file1:
Буква l в группе прав доступа к файлу сигнализирует нам о том, что этот файл является символьной ссылкой на другой файл, что также отражено в имени файла — symlink1 -> file1 .
Сравним индексные номера file1, hardlink1, hardlink2 и symlink1:
Видно, что индексный номер symlink1 отличается от других номеров, так как для файловой системы это уже два независимых объекта. Также заметно и различие в наборе прав.
Жесткие ссылки vs. Символьные ссылки
Ниже представлены основные различия между жесткими и символьными ссылками.
Жесткие ссылки:
не могут пересекать границы файловой системы (т.е. жесткая ссылка работает только в пределах своей файловой системы);
нельзя использовать с директориями;
имеют inode и разрешения исходного файла;
разрешения будут обновляться при изменении разрешения исходного файла;
связаны с содержимым исходного файла. Если вы создадите жесткую ссылку на файл и измените содержимое файла (или ссылки), то изменения будут присутствовать в обоих объектах;
с помощью жесткой ссылки вы можете просматривать содержимое файла, даже если исходный файл перемещен или удален.
Символьные ссылки:
могут пересекать границы файловой системы;
можно использовать с директориями;
имеют свои собственные (отдельные) inode и права доступа;
разрешения не будут обновляться;
связаны только с именем (путем) исходного файла, а не с его содержимым; удаление символьной ссылки не приводит к удалению файла;
можно изменить имя, атрибуты самой ссылки или перенаправить её ссылаться на другой файл, и при этом исходный файл затронут не будет (но имейте ввиду, что если вы по ссылке откроете для редактирования сам файл, то внесете изменения непосредственно в исходный файл).
Удаление ссылок
Если вы удалите жесткую ссылку, то связанный с ней файл будет существовать, пока существует хотя бы одна жесткая ссылка на него. Если вы удалите исходный файл, но при этом в другом месте сохранится жесткая ссылка на него, то «сменится» каталог размещения файла. В качестве примера добавим в наш file1 строку «Welcome to Ravesli.com» , удалим файл, а затем попробуем обратиться к жесткой ссылке hardlink2:
Обратите внимание, несмотря на то, что исходного файла больше нет, мы все еще можем получить доступ к его содержимому, используя жесткую ссылку.
При удалении файла, на который указывает символьная ссылка, сама ссылка просто станет нерабочей. Например, удалим файл file1, на который у нас есть символьная ссылка symlink1:
Символьная ссылка превратилась в «висячую» ссылку, указывая на несуществующий файл. Если попытаться к ней обратиться, то система выдаст нам сообщение об ошибке:
$ file file1
file1: cannot open `file1′ (No such file or directory)
diego@debian:
$ file symlink1
symlink1: broken symbolic link to file1
diego@debian:
Заключение
Ссылки являются неотъемлемой частью Linux-систем и часто помогают в навигации и изучении файловой системы. Если у вас остались какие-то вопросы, то не стесняйтесь задавать их в комментариях.
Поделиться в социальных сетях:
Изучаем процессы в Linux. Управление процессами
Источник
How to create a hard links in Linux or Unix
How to create a hard links in Linux or Unix
To create a hard links on a Linux or Unix-like system:
- Create hard link between sfile1file and link1file, run: ln sfile1file link1file
- To make symbolic links instead of hard links, use: ln -s source link
- To verify soft or hard links on Linux, run: ls -l source link
Let us see examples to make a hard link on a Linux / Unix systems.
ln command example to make a hard link on a Linux
The ln command make links between files. By default, ln makes hard links.
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
ln Command Syntax T Create Hard Link in Linux
The syntax is as follows for Unix / Linux hard link command:
- source is an existing file.
- link is the file to create (a hard link).
To create hard link for foo file, enter:
echo ‘This is a test’ > foo
ln foo bar
ls -li bar foo
Sample outputs:
- 4063240 : Inode. From the above sample output we can see that inodes are identical. We passed the -i option to the ls command to display the index number of each file (inodes).
- 2 : The number of hard links to file is shown in the third column. So if you run, ln foo hlink2 , the counter will increase to three.
How do I delete a hard link on Linux or Unix?
The rm command deletes files on Linux or Unix including a hard link. However, data is still accessible as long as another hard link exists even if you delete source file. To get rid of data you must remove all hard links including source.
Use the rm command:
$ echo ‘I love Linux and Unix’ > file.txt
$ cat file.txt
## create hard links ##
$ ln -v file.txt hardlink1
$ ln -v file.txt hardlink2
## list all files with inodes ##
$ ls -li file.txt hardlink?
## remove 1st hardlink ##
$ rm hardlink1
$ ls -li file.txt hardlink?
## remove source file ##
$ rm file.txt
$ ls -li file.txt hardlink?
## but we can still access original file.txt data ##
$ cat hardlink2
## to get rid of file.txt data delete all hard links too ##
$ rm hardlink2
## error error all data gone ##
$ cat file.txt hardlink?
$ ls -li file.txt hardlink?
Hard Links Limitations on Linux and Unix
There are some issues with hard links that can sometimes make them unsuitable. First of all, because the link is identical to the thing it points to, it becomes difficult to give a command such as “list all the contents of this directory recursively but ignore any links”. Most modern operating systems don’t allow hard links on directories to prevent endless recursion. Another drawback of hard links is that they have to be located within the same file system, and most large systems today consist of multiple file systems.
Источник
Everything Important You Need to Know About Hard Link in Linux
Before you see hard links, I advise you to learn about inodes in Linux. A Linux filesystem has two main components: a pool of data blocks where data is stored and a database system to manage this data pool. The inode is like index to this database system.
What is hard link in Linux?
A hard link to a file points to the inode of the file instead of pointing to the file itself. This way the hard link gets all the attributes of the original file and points to the same data block as the original file.
If you remember the symbolic link or the soft link, you know that it points to the file. A hard link is a manually created entry in a directory that points to an already existing inode.
I am going to explain it to you with proper diagrams. Let’s take this directory structure for example:
Filesystem representation
So basically, root directory contains dir_1 and dir_2 directories. The dir_1 directory has file_1 and file_2 files whereas dir_2 contains file_3 and a hard link to the file 2.
Let’s see how things look like in the filesystem. Everything is representational. In reality, the root directory will have thousands of files. Here, we assume it to have only two directories.
Inode Linux Filesystem
Remember the Linux directory structure? You start with the root (/). The root directory always has inode 2.
If you have to access the file 3, the absolute path would be /dir_2/file_3. In here, you can read it like this: you start at inode 2 (root always indoe 2) and follow the arrow to its data block. This data block has the information about the inode of the dir_2 (inode 27 in our example).
Now you look into inode 27. Its type is directory. You follow to its data block that has information about the inode of file_3 (inode 88). You look into the inode 88. Its type is file and if you follow to its data block, you access the content of the file.
Did you notice that the directory itself doesn’t content its file’s data? Directories are essentially a file that contain the information about the inodes of their files and subdirectories.
You must be wondering about the link count thing in the above image. That’s super important specially when you are dealing with hard link. The link count is the number of directory entries that point to an inode. Take inode 27 for dir_2 for example. The inode 27 is once in the data block of the root directory and once in its own data block (the special directory .). And hence it has link count of 2.
Notice that all the files have link count 1 except file_2? If a file has link count more than 1, it means there are hard links ‘to this file’. Since hard links point to the same inode (inode 17 in our example) as the target file, you get 2 directory listings for inode 17 (in data block of dir_1 and dir_2).
How to create hard links in Linux
You can use the ln command in order to create a hard link:
This will create a hard link named link_name to the target_file. You’ll see that link_name looks like a regular file and its attributes are the same as the target file.
If you use the ls -li command (the -i option shows the inode number), you’ll see that its link count is 2. The link count is after the file permission field.
Both have the same inode number 134195, obviously.
Things to keep in mind about hard links
Now that you have a good idea about hard links in Linux let’s take things a bit further.
Deleting the target file won’t delete its data anymore if it has hard link
If you delete the target file, you can still access its content through the hard link. It’s because both target file and hard link has the same inode and thus they point to the same data block.
Deleting files in Linux is basically unlinking. Suppose you delete the file_1 using rm command. The Linux kernel will find that file_1 corresponds to inode 16. It will remove file_1 entry from dir_1’s listing and reduce the inode 16’s link count by 1. Now that inode 16’s link count is 0, the kernel knows that there are no one linking to this inode so it is safe to remove the inode and delete the data block associated with it.
Now say you delete file_2. Kernel will remove the file_2 from dir_1’s listing and will go to inode 17. It will reduce the link count of inode 17 bringing it down to 1. Since the link count is not zero, the kernel will not delete the inode or the data associated with it. And hence, if you access the hard link, you can still access the data even though the original file has been deleted.
You should not create a hard link to a directory
You can create a soft link to a directory but when you try to create a hard link to a directory, you’ll see an error like this:
Why are hard links not allowed for directory? It’s because using hard links for directory may break the filesystem. Theoretically, you can create hard link to directories using -d or -F option. But most Linux distributions won’t allow that even if you are root user.
It’s nearly impossible to distinguish between the hard links and the original file
Let’s have another look at the hard link I created earlier:
They have identical attributes but you can guess which is the link based on the name in the above example but what if the name wasn’t obvious? How would you know if their names were target_1 and target_2?
If the file and link(s) are in a different directory, you may try checking the mtime and other parameters to know when the content of the directory was changed but even that is not a certainty. If the file and hard link is in the same directory and the history has been wiped out, I am not sure how can you figure out which is the original file and which is the hard link.
Bonus Tip: How to find all hard links to a given file
If you see that a file has more than one link count, you may get curious about the other hard links associated with it.
One way to find that is using the inode number of the file. You can use the ls -i command or the stat command to get the inode number.
Once you have the inode number, you can see all the links associated with it using the find command.
Was it hard to understand the hard links?
I hope it wasn’t too ‘hard’ and you have a better understanding of the concept of hard link in Linux. If you have doubts or suggestions on this topic, please leave a comment below.
Источник