Linux create hard link

To create a hard links on a Linux or Unix-like system:

  1. Create hard link between sfile1file and link1file, run: ln sfile1file link1file
  2. To make symbolic links instead of hard links, use: ln -s source link
  3. 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.

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

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.

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?

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.

Источник

In Unix-like operating systems such as Linux, “everything is a file” and a file is fundamentally a link to an inode (a data structure that stores everything about a file apart from its name and actual content).

Читайте также:  Windows настройка загрузка восстановление

A hard link is a file that points to the same underlying inode, as another file. In case you delete one file, it removes one link to the underlying inode. Whereas a symbolic link (also known as soft link) is a link to another filename in the filesystem.

Another important difference between the two types of links is that hard links can only work within the same filesystem while symbolic links can go across different filesystems.

To create a hard links in Linux, we will use ln utility. For example, the following command creates a hard link named tp to the file topprocs.sh .

Create a Hard Link to File

Looking at the output above, using ls command, the new file is not indicated as a link, it is shown as a regular file. This implies that tp is just another regular executable file that points to the same underlying inode as topprocs.sh .

To make a hard link directly into a soft link, use the -P flag like this.

To create a symbolic links in Linux, we will use same ln utility with -s switch. For example, the following command creates a symbolic link named topps.sh to the file topprocs.sh .

Create a Symbolic Link to File

From the above output, you can see from the file permissions section that topps.sh is a link indicated by l: meaning it is a link to another filename.

If the symbolic link already exist, you may get an error, to force the operation (remove exiting symbolic link), use the -f option.

Forcefully Create Symbolic Link

To enable verbose mode, add the -v flag to prints the name of each linked file in the output.

Enable Verbose in Command Output

That’s It! Do check out these following related articles.

In this article, we’ve learned how to create hard and symbolic links in Linux. You can ask any question(s) or share your thoughts about this guide via the feedback form below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

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

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

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

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

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

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

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

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

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

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

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

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

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

Читайте также:  Windows 10 выключить microsoft store

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

Рассмотрим опции утилиты:

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

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

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

mkdir test && cd test

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

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

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

ln -s source softlink

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

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

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

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

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

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

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

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

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

ln source hardlink

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

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

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

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

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

Выводы

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

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

Источник

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.

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.

Читайте также:  Как сделать панель пуск прозрачной windows 10

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).

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.

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 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.

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.

Источник

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