What is symlink in linux

Estamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.

A symbolic link, or symlink, creates a name that references another file, directory, or other Linux file system object. Using symlinks minimizes the necessity of having multiple copies of a file within a system. Any changes can be made in one place, instead of modifying many copies.

Symlinks also provide a way to manage access. Multiple directories each owned by a user can reference a subset of a set of files. This limits visibility in a more complex manner than the file system permissions system permits.

Symlinks are a vital tool to file management and organization.

A symlink is a type of special file whose “data” is a path to the name of a file system object, which could be a:

  • file
  • directory
  • pipe — via mkfifo
  • special device
  • symlink — see Chains of Soft Links below

Also known as a “soft link” in Linux, the term “shortcut” describes symlinks in other operating systems.

It is easy to confuse a symlink with a hard link. A disk’s file system has a number of control blocks called inodes. These describe the details of files and other objects, including where on the disk any associated data is stored. Entries in a Linux directory associate a name, for example “config”, with an inode number. A hard link creates an alias, or an associated name with the same inode number. See the man page for the ln utility for details, particularly limitations on creating and removing hard links.

The symlink (AKA soft link) is a referrer rather than an alias. Think of it as a signpost pointing to where the target file can be found. The Linux system reads the symlink’s file path to reach the target.

Soft links make restoring backups easier than doing so with hard links. Use of symlinks can simplify the installation or update of an application or file system tree.

Symlinks can be used in special cases where the symlink points to another symlink. The Linux system progresses down such a chain of symlinks to get to the final object. When you unlink the head of a symlink chain, you remove only that symlink. When you unlink an intermediate symlink, you break the chain. In both cases, the target remains untouched.

To prevent chain loops from overloading the system, Linux limits the number of hops through a symlink chain to 40.

Читайте также:  Server installation in linux

To see all the nodes in a symlink chain, use the namei command. Here is sample output from one computer:

d . d Desktop d backup.per d satch d Desktop d ietf d rfcs l in-notes -> in-notes l in-notes -> in-notes l in-notes -> in-notes l in-notes -> in-notes …

The command follows from the specified directory down the file system tree. In this case, one of the symlinks points to itself – a chain loop that’s pretty direct.

There are various ways to create symbolic links depending on how you want to use them. The basic syntax to create a symlink is as follows:

The -s switch is important because it tells the Linux ln command to create a soft link instead of a hard link. The is optional. If not specified, the symlink is created in the current working directory.

The following example command creates the symlink-file symlink in the current directory, which points to /tmp/reference-file :

In this example, the file pathname is absolute. You can create a symlink with a relative path. However, make sure that anything using the symlink first sets the current working directory, otherwise the link is broken.

The same command can also be used to create a symlink that points to a directory. The following example command creates the symlink-directory symlink in the current directory, which points to /tmp/reference-directory :

Any reference to symlink-directory acts on the directory /tmp/reference-directory . This includes adding or deleting files in the directory, changing the ownership, and changing the permission if allowed.

If the path in a symlink is wrong, for example a typo, or the target has moved, you can update the link using the -f flag:

This results in the old symlink’s contents being replaced with the new. The -f switch automatically removes any conflicting symlink-filepath files or symlinks if there is a conflict. Making a symlink without the -f switch, using a sympath-name that is already in use, results in the command failing.

To show the contents of a symlink, use the Linux ls command:

The output looks like this:

symlink-file -> /tmp/reference-file

Almost all file-based actions on a symlink act on or affect the target file, but not the symlink or symlink chain itself. Therefore touch , chmod , chown , chgrp , shell redirection, and their program/script equivalents all act on the target file/directory and its attributes. When the file is open, all read and write activity accesses or modifies the target file. However, there are exceptions, described in the next section.

The exceptions to the above-described rule are the Linux commands unlink , rm , rmdir , and their associated system calls. These commands either fail or remove the symlink itself instead of the target file or directory. These exceptions prevent the inadvertent removal of the target.

See more information about removing symlinks in our Remove Symbolic Links.

A dangling symlink occurs when the target does not exist. The original file may have been deleted or moved to another part of the file system tree.

Читайте также:  Linux отключить энергосберегающий режим

While breaking a symlink can be intentional, dangling symlinks can clutter up the file system if not intended. To find these dangling symlinks within a file system tree, use this command:

Do not immediately pipe this to the rm command. Investigate first, so you can repair inadvertently broken symlinks.

Conclusion

Symlinks help reduce clutter and maintenance when many applications use a common file. When a sysadmin changes the common file, it affects all applications using it, in one simple operation. Using symlinks is an alternative to using directories like /etc (which requires root access) to store such much-used files. Moreover, the application developer can use a local file for testing and debugging. Then upon release, replace that local file with the symlink to the production version of the application.

If a portion of the file system tree expands to overflow the disk partition, move that tree to another partition, perhaps on another disk. Then replace the top of that tree with a symlink pointing to its new home. This method of doing disk maintenance reduces the clutter in /etc/fstab by associating the new location to the old.

More Information

You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

This page was originally published on Tuesday, April 18, 2023.

Источник

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Выводы

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

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

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

Источник

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