Linux symlink to file

linux-notes.org

Хотелось бы рассказать как можно создавать ссылки (симлинки) в ОС Unix/Linux. В своей теме «Создание ссылок (symlink) в Unix/Linux» я на готовом примере покажу как это делается. Существуют несколько видов ссылок, и я расскажу в чем разница между ними.

Симлинк или мягкая ссылка представляет собой особый тип файла, который содержит ссылку на другой файл или каталог в виде абсолютного или относительного пути.

Жёсткой ссылкой — это структурная составляющая файла которая описывает его элемент каталога.

В этом подразделе, я расскажу какие бывают симлинки и в чем они отличаются.

Мягкая ссылка (Soft link):

  1. Мягкие ссылки используют различные номера инод чем основные файлы.
  2. Мягкие ссылки становится полезными, если исходный файл был удален.
  3. Мягкие ссылки могут быть созданы из каталогов.
  4. Мягкая ссылка может быть создана на пересечении файловых систем.

Для того чтобы создать симлинк в линукс используется следующая команда:

И так, я создал симлинк linux-notes.org.conf на на тот же файл но который будет расположен в другой директории. После создания симлинка, необходимо сменить права на него:

Для проверки номера иноды:

Я создал симлинк на файл, так же, можно создавать симлинка на целую папку, для этого используйте:

И так, я создал симлинк symlink-to-opt-dir на папку /opt/directory. После создания симлинка, необходимо сменить права на него:

Вот и все, очень просто, и полезно.

Для проверки номера иноды:

Чтобы удалить, используйте:

И аналогично для каталогов.

Если вы удалите мягкую ссылку (/home/captain/linux-notes.org-softlink.txt), то сам файл данных будет по-прежнему находится там же (/home/captain/linux-notes.org.txt). Тем не менее, если вы удалите /home/captain/linux-notes.org.txt, то /home/captain/linux-notes.org-softlink.txt станет сломанной ссылкой и данные будут потеряны.

Жесткие ссылки (Hard Links):

  1. Жесткие ссылки использует тот же номер иноды что и основные файлы.
  2. Нельзя создать жесткие ссылки на каталоги.
  3. Жесткие ссылки не могут быть созданы на пересечении файловых систем.
  4. Жесткие ссылки всегда относится к источнику, даже если они перемещаются или удаляется.

Чтобы создать «жесткую ссылку», используйте:

Проверяем номер иноды:

Оба файла имеют одинаковые иноды (одинаковое количество индексных дескрипторов). Если нужно удалить «жесткую ссылку», то используйте команду:

Если вы удалите жесткую ссылку, ваши данные будут там. Если вы удалите /home/captain/linux-notes.org.txt то файл будет по-прежнему доступен через жесткую ссылку

Жесткие ссылки (Hardlink) vs Мягкие ссылки (Softlink) в UNIX/Linux

  • Как я говорил ранее, жесткие ссылки не могут быть созданы для директорий.
  • Жесткие ссылки не могут использоваться на пересечении границ файловых систем ( Нельзя создать сылку /tmp и примонтированную на /tmp ко 2-му HDD который смонтирован на/harddisk2).
  • Символические ссылки (мягкие ссылки) ссылаются на символичный путь с указанием абстрактного расположение другого файла.
  • Жесткие ссылки, ссылаются к определенному местоположению физических данных.

На этом, моя тема «Создание ссылок (symlink) в Unix/Linux» завершена. Не сильно сложная тема, но очень полезная.

Источник

Symbolic links can be made to directories as well as to files on different filesystems or different partitions.

  • symbolic links (also known as “soft links” or “symlinks”): Refer to a symbolic path indicating the abstract location of another file.
  • hard links : Refer to the specific location of physical data.

Soft links are created with the ln command. For example, the following would create a soft link named link1 to a file named file1, both in the current directory
$ ln -s file1 link1
To verify new soft link run:
$ ls -l file1 link1
Sample outputs:

  • 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
Читайте также:  Включение подсистемы windows для linux

Join Patreon

From the above outputs it is clear that a symbolic link named ‘link1’ contains the name of the file named ‘file1’ to which it is linked.

How to use the ln command

So the syntax is as follows to create a symbolic link in Unix or Linux, at the shell prompt:
$ ln -s < source-filename >< symbolic-filename >

For example create a softlink for /webroot/home/httpd/test.com/index.php as /home/vivek/index.php, enter the following command:
$ ln -s /webroot/home/httpd/test.com/index.php /home/vivek/index.php
$ ls -l
Sample outputs:

You can now edit the soft link named /home/vivek/index.php and /webroot/home/httpd/test.com/index.php will get updated:
$ vi /home/vivek/index.php
Your actual file /webroot/home/httpd/test.com/index.php remains on disk even if you deleted the soft link /home/vivek/index.php using the rm command:
$ rm /home/vivek/index.php ## ##
## But original/actual file remains as it is ##
$ ls -l /webroot/home/httpd/test.com/index.php

The syntax remains same:
$ ln -s
For example, create a symbolic link from the /home/lighttpd/http/users/vivek/php/app/ directory to the /app/ directory you would run:
$ ln -s /home/lighttpd/http/users/vivek/php/app/ /app/
Now I can edit files using /app/
$ cd /app/
$ ls -l
$ vi config.php

Pass the -f to the ln command to overwrite links:
ln -f -s /path/to/my-cool-file.txt link.txt

Use the rm command to delete a file including symlinks:
rm my-link-name
unlink /app/
rm /home/vivek/index.php

Getting help about the ln command

Type the following ln command:
$ man ln
$ ln —help

ln command option Description
—backup make a backup of each existing destination file
-b like —backup but does not accept an argument
-d allow the superuser to attempt to hard link directories (note: will probably fail due to system restrictions, even for the superuser)
-f remove existing destination files
-i prompt whether to remove destinations
-L dereference TARGETs that are symbolic links
-n treat LINK_NAME as a normal file if it is a symbolic link to a directory
-P make hard links directly to symbolic links
-r create symbolic links relative to link location
-s make symbolic links instead of hard links
-S override the usual backup suffix
-t specify the DIRECTORY in which to create the links
-T treat LINK_NAME as a normal file always
-v print name of each linked file
—help display this help and exit
—version output version information and exit

Conclusion

You learned how to create a symbolic link in Linux using the ln command by passing the -s option. See ln command man page here for more information.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

A symlink (also called a symbolic link) is a type of file in Linux that points to another file or a folder on your computer. Symlinks are similar to shortcuts in Windows.

Some people call symlinks «soft links» – a type of link in Linux/UNIX systems – as opposed to «hard links.»

Soft links are similar to shortcuts, and can point to another file or directory in any file system.

Hard links are also shortcuts for files and folders, but a hard link cannot be created for a folder or file in a different file system.

Let’s look at the steps involved in creating and removing a symlink. We’ll also see what broken links are, and how to delete them.

The syntax for creating a symlink is:

ln is the link command. The -s flag specifies that the link should be soft. -s can also be entered as -symbolic .

By default, ln command creates hard links. The next argument is path to the file (or folder) that you want to link. (That is, the file or folder you want to create a shortcut for.)

Читайте также:  Windows проверяет диск при каждой загрузке

And the last argument is the path to link itself (the shortcut).

After running this command, you will be able to access the /home/james/transactions.txt with trans.txt . Any modification to trans.txt will also be reflected in the original file.

Note that this command above would create the link file trans.txt in your current directory. You can as well create a linked file in a folder link this:

There must be a directory already called «my-stuffs» in your current directory – if not the command will throw an error.

Similar to above, we’d use:

This would create a symlinked folder called ‘james’ which would contain the contents of /home/james . Any changes to this linked folder will also affect the original folder.

Before you’d want to remove a symlink, you may want to confirm that a file or folder is a symlink, so that you do not tamper with your files.

One way to do this is:

Running this command on your terminal will display the properties of the file. In the result, if the first character is a small letter L (‘l’), it means the file/folder is a symlink.

You’d also see an arrow (->) at the end indicating the file/folder the simlink is pointing to.

There are two methods to remove a symlink:

This deletes the symlink if the process is successful.

Even if the symlink is in the form of a folder, do not append ‘/’, because Linux will assume it’s a directory and unlink can’t delete directories.

As we’ve seen, a symlink is just another file or folder pointing to an original file or folder. To remove that relationship, you can remove the linked file.

Hence, the syntax is:

Note that trying to do rm james/ would result an error, because Linux will assume ‘james/’ is a directory, which would require other options like r and f . But that’s not what we want. A symlink may be a folder, but we are only concerned with the name.

The main benefit of rm over unlink is that you can remove multiple symlinks at once, like you can with files.

Broken links occur when the file or folder that a symlink points to changes path or is deleted.

For example, if ‘transactions.txt’ moves from /home/james to /home/james/personal , the ‘trans.txt’ link becomes broken. Every attempt to access to the file will result in a ‘No such file or directory’ error. This is because the link has no contents of its own.

When you discover broken links, you can easily delete the file. An easy way to find broken symlinks is:

This will list all broken symlinks in the james directory – from files to directories to sub-directories.

Passing the -delete option will delete them like so:

Wrapping up

Symbolic link are an interesting feature of Linux and UNIX systems.

You can create easily accessible symlinks to refer to a file or folder that would otherwise not be convenient to access. With some practice, you will understand how these work on an intuitive level, and they will make you much more efficient at managing file systems.

Frontend Web Engineer and Technical Writer. I love teaching what I know. Javascript / ReactJS / NodeJS

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives and help pay for servers, services, and staff.

Источник

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

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

Читайте также:  Droidcam client для компьютера windows 10

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

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

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

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

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

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

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

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

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

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

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

$ 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:

Источник

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