Link folders in 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

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
Читайте также:  Npm install linux debian

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

Источник

Learning Linux symbolic commands is a great way of improving your potential in the Linux terminal. In this tutorial, we’ll cover a few commands to learn symbolic links in a quick and easy way. Before we begin, let’s overview what are symbolic links.

Symbolic Links are not only helpful in creating shortcuts and file management in operating systems like Linux. They also serve as a way to create various locations for primary user folders, for instance, Documents, Pictures, Downloads, and much more!

Symbolic Links act like a string creating pathways for different files, folders, and directories in the computer system. They are capable of creating and storing multiple files in different places refer to one single file. Thus, increasing efficiency by locating all the specific documents in one command.

These links are stored in the mainframe, so even if the original file is deleted, you’ll have a backup for most of the important files. Symbolic links help create invalid link pathways to store pieces of information as per the requirement of the user.

Due to the user-friendly features in Linux, even Microsoft is following it to create Symbolic Links. Symbolic links, also known as Soft links or Symlinks, are not unique to Linux but they are just like a Search option in Windows where one can search a specific file or directory in a disk by executing various commands.

Let’s look at how you can create file and folder links in Linux:

Generally, to create links use we use the ln command and the -s option to specify Symbolic links. This is the easiest way to ensure a flexible approach that allows experimenting with the language as much as possible. There is nothing hard in creating Symbolic links in Linux – you just need to follow one simple step.

The ln command in Linux creates links between source files and directories.

  • -s – the command for Symbolic Links.
  • [target file] – name of the existing file for which you are creating the link
  • [Symbolic filename] – name of the symbolic link.

Created links can be verified by directory listing using detailed list command:

However, if you do not specify the [Symbolic filename], the command will automatically create a new link in the existing directory.

Creating symbolic links for folders is not difficult either. The command used to create the folder symbolic link is:

For example, to link the /user/local/downloads/logo directory to /devisers folder, use the following command:

Once a Symbolic link is created and attached to the folder /devisers, it will lead to /user/local/downloads/logo. When the user changes directory – cd – to /devisers, the system will automatically change to the specific file and write it in the command directory.

Symbolic link options are called command line switches. Here are the most common ones and their descriptions:

Command Switch Description
–backup[=CONTROL] backup each existing destination file
-d, -F, –directory superuser is allowed to attempt hard link
-f, –force existing destination file is removed
-I, –interactive prompt before removing destination files
-L, –logical deference targets that are symbolic links
-n, –non-dereference symbolic links to directory are treated as files
-P, –physical make hard links directly to symbolic links
-r, –relative create symbolic links relative to link location
-s, –symbol make symbolic links instead of hard links
-S, –suffix=SUFFIX override usual backup suffix
-v, –verbose print name of each linked file
Читайте также:  Выключение компьютера через планировщик заданий windows

You can remove existing links attached to files or directories by the unlink or rm command. This is how you can do it with the unlink command:

Removing symbolic link using the rm command is similar to the unlink command which is as under:

Wrapping up

Remember, if the source is no longer in the current location, then you should delete the symbolic files to avoid creating duplicates, which might slow down your work.

Linux is a wonderful platform for creating an interactive and dynamic application, where you can experiment and innovate. A strong foundation is critical. Learn the basic of the language thoroughly to use it to its full potential. We hope this tutorial helped you improve your skills with another useful tool!

Edward is an expert communicator with years of experience in IT as a writer, marketer, and Linux enthusiast. IT is a core pillar of his life, personal and professional. Edward’s goal is to encourage millions to achieve an impactful online presence. He also really loves dogs, guitars, and everything related to space.

Источник

Symbolic link or soft link is a special type of file that contains a reference, which points to another file or directory. It is supported on almost all Linux distributions. Although it points to their target, they operate independently of their targets. We can create links for both files and directories.

Removing symbolic link doesn’t affect anything but when the original file is removed, the link becomes a ‘dangling’ link that points to a nonexistent file. Unlike hard link, soft links have different inode numbers, ie deleting target file or directory does not remove soft links. These links could be also created across the filesystem.

ln command is used to create symbolic links and it uses the following syntax:

For example, to link the /usr/local/lib/sample directory to /sample folder, use the following command:

After creating the symbolic link to the folder /sample and it should point to /usr/local/lib/sample, and when user changes directory (cd) to /sample, Operating system shell will automatically change to /usr/local/lib/sample directory. You can view link using ls command. You might have noticed, file type field is showing l that indicates that it is a symbolic link and -> shows link path.

The symbolic link could be used for files also using the same ln command. Below, example will show how to create a new link (soft) file «filesync» which point to /home/bobbin/sync.sh

This will create a new link file named selfi.sh in the current directory which will point to /home/bobbin/selfi.sh

Conclusion

Symbolic links are used for linux programs, as aliased so that users does not have to know which version of code used.

Don’t use soft links as an alternative for backup. Backup is two identical set of data where links are alias names for file or directory.

Источник

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

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

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

Читайте также:  При запуске windows открывается cmd

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

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

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

  • Могут ссылаться на файлы и каталоги;
  • После удаления, перемещения или переименования файла становятся недействительными;
  • Права доступа и номер 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:

Источник

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