Creating linux link files

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:

Читайте также:  Chrome browser windows downloads

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

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.

Читайте также:  Образ windows 10 64 bit для флешки iso без лишнего

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

Источник

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.
Читайте также:  Iccup для mac os

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

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

Источник

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