Linux show link target

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

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

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

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

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

Читайте также:  Драйвер для сканера benq 5250c для windows 10

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

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

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

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

ln source hardlink

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

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

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

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

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

Выводы

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

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

Источник

In your Linux file system, a link is a connection between a file name and the actual data on the disk. There are two main types of links that can be created: «hard» links, and «soft» or symbolic links. Hard links are low-level links which the system uses to create elements of the file system itself, such as files and directories.

Most users do not want to create or modify hard links themselves, but symbolic links are a useful tool for any Linux user. A symbolic link is a special file that points to another file or directory, which is called the target. Once created, a symbolic link can be used in place of the target file name. It can have a unique name, and be located in any directory. Multiple symbolic links can even be created to the same target file, allowing the target to be accessed by multiple names.

The symbolic link is a file in its own right, but it does not contain a copy of the target file’s data. It is similar to a shortcut in Microsoft Windows: if you delete a symbolic link, the target is unaffected. Also, if the target of a symbolic link is deleted, moved, or renamed, the symbolic link is not updated. When this happens, the symbolic link is called «broken» or «orphaned,» and will no longer function as a link.

One way to create a symbolic link in the X Windows GUI is with your file manager. Some Linux distributions use different file managers, but the process is similar. Locate a target file in your file manager GUI, highlight it by clicking it once, and select the «create a link» option. This option is usually found under the Edit menu, or in the context menu that appears when you right-click the highlighted file.

In the example shown above, using the Thunar file manager, we have highlighted the file myfile.txt, then selected Make Link in the Edit menu. After completed, a new symbolic link called link to myfile.txt is created. This link can be renamed or moved to another location. It always points to the target, unless the target is later moved or deleted, resulting in the link becoming orphaned.

The command line is a powerful tool in Linux because it gives you greater control over your commands. (For more information about the command line, and how to access it from Linux, see our Linux and Unix shell tutorial).

You can create symbolic links using the ln command’s -s option. The general syntax for creating a symbolic link is:

For instance, if we have a file in our working directory called myfile.txt, and we want to create a symbolic link in the same directory called mylink, we could use the command:

In this command, we have opened a terminal session that places us at our shell’s command prompt. We are logged in a system named myhost as a user named user, and our working directory is a folder in our home directory called myfolder:

First, let’s use ls with the -l option to produce a long list of all the files in our directory:

Читайте также:  Epic games launcher mac os не запускается

We see our file, myfile.txt, which is the only file in the directory. («total 4» refers to how many blocks on the disk are used by the files listed, not the total number of files).

Let’s use the cat command to view the contents of myfile.txt:

Now, let’s create a symbolic link to mylink.txt called mylink using the ln -s command:

It seems like nothing happened, but this means it worked as expected. If there was an error, or if an unexpected condition was encountered, we would receive a notification.

Now, if we do another ls -l, we see two files — our target and our link:

One of the benefits of doing a long listing with «-l» is that we see extra information in addition to the file name. Notice the «l» at the beginning of the line containing our link name, indicating that the file is a symbolic link. Also, after mylink (in blue text) is the «->» symbol, followed by the name of the target.

Most shells, by default, are configured to display certain file types in different colors, but your terminal might show different colors or none at all.

Now, let’s use our symbolic link. If we run cat on it, it displays the contents of myfile.txt:

We can rename our link with mv, and it still points to the same target:

But what happens if we move our link somewhere else? In this case, our link breaks. We can see this by making a new directory using mkdir, and moving the link into the new directory using mv:

You can see that when we view the contents of directory newfolder with ls -l, our link is highlighted in red, indicating that it is a broken link. If we try to cat the contents of the link, the shell informs us that the file does not exist. It points to «myfile.txt» with no other path information. Therefore, the operating system looks for myfile.txt in the same directory as the link.

Let’s start over by removing newfolder and its contents using the command rm -r:

This time, let’s create the symbolic link using the absolute path to myfile.txt. Let’s double check the name of our working directory using pwd:

Our working directory is /home/user/myfolder, so let’s include this in the target name when we create the link:

As you can see from the output of ls -l, our link now points to the file /home/user/myfolder/myfile.txt. With this path information, we can move the link to another location, and it still points to our target:

Your bash shell keeps an environment variable called $PWD that always stores the value of your working directory. You can use this variable to insert the full path before your target name, as long as the target is in your working directory. We can view the value of $PWD using the echo command:

This text is inserted if we use $PWD as part of a command. It is a good idea to enclose it in quotes as «$PWD» in case the directory name has any spaces. The quotes make sure the shell knows they are part of the pathname and not command separators.

Here is our command, and a directory listing to show that it worked:

Источник

A symbolic link, also known as a symlink or a soft link, is a special type of file that simply points to another file or directory just like shortcuts in Windows. Creating symbolic link is like creating alias to an actual file.

If you try to access the symbolic link, you actually access the target file to which the symlink points to. Changes performed on the content of the link file changes the content of the actual target file.

If you use the ls command with option -l, this is what a symbolic link looks like:

In most Linux distributions, the links are displayed in a different color than the rest of the entries so that you can distinguish the links from the regular files and directories.

Читайте также:  График выхода windows ltsc

Soft Link displayed in different color

Symbolic links offer a convenient way to organize and share files. They provide quick access to long and confusing directory paths. They are heavily used in linking libraries in Linux.

Now that you know a little about the symbolic links, let’s see how to create them.

To create a symbolic link to target file from link name, you can use the ln command with -s option like this:

The -s option is important here. It determines that the link is soft link. If you don’t use it, it will create a hard link. I’ll explain the difference between soft links and hard links in a different article.

Symbolic links could be confusing at times therefore you should keep note of a few things.

That’s the whole purpose of the links after all. You access the target file by accessing the link. You can make changes to the target file through the links. Let’s see with example.

I have a file prog.py in newdir/test_dir. It has the following attributes:

Now, I’ll create a soft link to this file in my present directory:

Here are the attributes of the newly created link:

Notice the l (it’s L, not one) at the beginning of the line? If you are familiar with the file permissions in Linux, you would know that the ‘l’ signifies link and thus it tells you that this file is actually a link. To refresh your memory, – means file, and d means directory.

Now if I use this link to change the content or the attributes, the same will be reflected in the target file. For example, I am using touch command on the soft link and you’ll notice that it changes the timestamp of the target file.

How would you know if the link points to file or a directory? You cannot know that until you follow the path and access the target file itself.

Yes, that’s totally possible. This is why you should be careful while creating soft links in Linux. The target file to which you are linking doesn’t need to exist. You won’t get any error or warning for creating link to a file/directory that does not exist.

You’ll get error only when you try to access the target file, either through the link or on its own. The ls command will still work though.

Did you notice the file permission on the symbolic link? The symlinks are always created with 777 permission (rwxrwxrwx). For regular file, this would mean that anyone can access the file. But that’s not the case for the links.

If the file permissions on the links were treated as it is, any user could create a symlink to a secure file and access it freely. That would be a major security issue. Thankfully, that doesn’t happen. Because the permission on the target files matter, not the permission on links.

You may use the chmod command to change the permission on the link but it will change the permission of the linked file, not the link itself.

You can make a symbolic link that points to another link and so on. This is called chained symbolic link. It’s better to avoid them as it creates more confusion.

Well, that’s it. I presume you have a better knowledge of the soft links now and you know how to create symbolic links in Linux. You may read about the symlinks command that can help you find broken symlinks in Linux and manage them easily.

If you have questions or suggestions, please leave a comment below.

Источник

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