Link in linux with directories

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

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.

Читайте также:  Windows 10 будет заниматься

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.

Источник

To create a hard links on a Linux or Unix-like system:

  1. Create hard link between sfile1file and link1file, run: ln sfile1file link1file
  2. To make symbolic links instead of hard links, use: ln -s source link
  3. To verify soft or hard links on Linux, run: ls -l source link

Let us see examples to make a hard link on a Linux / Unix systems.

The ln command make links between files. By default, ln makes hard links.

  • 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

The syntax is as follows for Unix / Linux hard link command:

  • source is an existing file.
  • link is the file to create (a hard link).

To create hard link for foo file, enter:
echo ‘This is a test’ > foo
ln foo bar
ls -li bar foo
Sample outputs:

  • 4063240 : Inode. From the above sample output we can see that inodes are identical. We passed the -i option to the ls command to display the index number of each file (inodes).
  • 2 : The number of hard links to file is shown in the third column. So if you run, ln foo hlink2 , the counter will increase to three.

The rm command deletes files on Linux or Unix including a hard link. However, data is still accessible as long as another hard link exists even if you delete source file. To get rid of data you must remove all hard links including source.

Use the rm command:
$ echo ‘I love Linux and Unix’ > file.txt
$ cat file.txt
## create hard links ##
$ ln -v file.txt hardlink1
$ ln -v file.txt hardlink2
## list all files with inodes ##
$ ls -li file.txt hardlink?
## remove 1st hardlink ##
$ rm hardlink1
$ ls -li file.txt hardlink?
## remove source file ##
$ rm file.txt
$ ls -li file.txt hardlink?
## but we can still access original file.txt data ##
$ cat hardlink2
## to get rid of file.txt data delete all hard links too ##
$ rm hardlink2
## error error all data gone ##
$ cat file.txt hardlink?
$ ls -li file.txt hardlink?

There are some issues with hard links that can sometimes make them unsuitable. First of all, because the link is identical to the thing it points to, it becomes difficult to give a command such as “list all the contents of this directory recursively but ignore any links”. Most modern operating systems don’t allow hard links on directories to prevent endless recursion. Another drawback of hard links is that they have to be located within the same file system, and most large systems today consist of multiple file systems.

Источник

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 10 комбинация

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

Источник

Основы Linux от основателя Gentoo. Часть 1 (3/4): Ссылки, а также удаление файлов и директорий

Третий отрывок из перевода первой части руководства. Предыдущие: первый, второй.

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

Создание ссылок и удаление файлов

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

Мы уже упоминали термин «ссылка», когда рассказывали о взаимоотношениях между директориями (их именами) и инодами (индексным номерами, лежащими в основе файловой системы, которых мы не замечаем). Вообще в Linux существует два типа ссылок. Тип, о котором мы уже говорили ранее, называется «жесткие ссылки». Каждый инод может иметь произвольное число жестких ссылок. Когда уничтожается последняя жесткая ссылка, и не одна программа не держит файл открытым, то Linux автоматически удаляет его. Новые жесткие ссылки можно создать воспользовавшись командой ln:

Как видите, жесткие ссылки работают на уровне инодов, для указания конкретного файла. В Linux системах, для жестких ссылок есть несколько ограничений. В частности, можно создавать жесткие ссылки только на файлы, не на директории. Да-да, именно так; хотя «.» и «..» являются созданными системой жесткими ссылками на директории, вам (даже от имени пользователя «root») не разрешается создавать любые свои собственные. Второе ограничение жестких ссылок состоит в том, что нельзя связать ими несколько файловых систем. Это значит, что у вас не получится создать жесткую ссылку с /usr/bin/bash на /bin/bash и если ваши директории / и /usr находятся в разных файловых системах (разделах — прим. пер.).

Символьные ссылки

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

Символические ссылки можно создать передав для ln опцию -s.

В выводе ls -l символьные ссылки можно отличить тремя способами. Во-первых, обратите внимание на символ l в первой колонке. Во-вторых, размер символической ссылки равен количеству символов в ней (secondlink в нашем случае). В-третьих, последняя колонка в выводе показывает куда ведет ссылка с помощью интуитивного обозначения «->».

Симлинки детально

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

Предположим, что мы хотим создать ссылку в /tmp, которая указывает на /usr/local/bin. Нам следует набрать:

Либо, альтернативный вариант:

Как вы видите, обе символические ссылки указывают на одну директорию. Однако, если наша вторая символьная ссылка когда-нибудь будет перемещена в другую директорию, то она может «поломаться» из-за относительности пути:

Читайте также:  Создание сервера windows или linux

$ mkdir mynewdir
$ mv bin2 mynewdir
$ cd mynewdir
$ cd bin2
bash: cd: bin2: No such file or directory

Потому, что директории /tmp/usr/local/bin не существует, мы больше не можем переместиться в bin2; другими словами, bin2 сейчас сломана.

По этой причине, избегать создания ссылок с относительной информацией о пути, иногда будет хорошей идеей. Тем не менее, существует множество случаев, где относительные символические ссылки крайне удобны. Рассмотрим пример в котором мы хотим создать альтернативное имя для программы в /usr/bin:

От имени суперпользователя мы хотим короткий синоним для keychain, такой, как kc. В этом примере у нас есть root-доступ, о чем свидетельствует измененное на «#» приветствие bash. Нам нужен root-доступ потому, что обычные пользователи не имеют прав создавать файлы в /usr/bin. От имени суперпользователя мы можем создать альтернативное имя для keychain следующим образом:

В этом примере мы создали символьную ссылку под названием kc, которая указывает на файл /usr/bin/keychain.

Пока это решение будет работать, но создаст проблему, если мы решим переместить оба файла, /usr/bin/keychain и /usr/bin/kc в /usr/local/bin:

Поскольку мы использовали абсолютный путь для символической ссылки kc, то она все еще ссылается на /usr/bin/keychain, которого не существует с тех пор как мы переместили /usr/bin/keychain в /usr/local/bin.

Это привело к тому, что симлинк kc сейчас не работает. Как относительные, так и абсолютные пути в символьных ссылках имеют свои достоинства, и, в зависимости от вашей задачи, нужно использовать соответствующий тип пути. Часто, и относительный, и абсолютный путь, будут работать одинаково хорошо. Пример ниже будет работать, даже после перемещения обоих файлов:

# mv keychain kc /usr/local/bin
# ls -l /usr/local/bin/keychain

Теперь, мы можем запустить программу keychain набрав /usr/local/bin/kc. /usr/local/bin/kc указывает на программу keychain в той же директории, где находится kc.

Итак, мы знаем как использовать cp, mv и ln, настало время узнать о том, как можно удалять объекты из файловой системы. Обычно это делается с помощью команды rm. Чтобы удалить файлы, просто укажите их в командной строке:

$ rm file1 file2
$ ls -l file1 file2
ls: file1: No such file or directory
ls: file2: No such file or directory

Имейте ввиду, что под Linux, однажды удаленный файл, обычно исчезает на века. Поэтому многие начинающие системные администраторы используют опцию -i, когда удаляют файлы. Опция -i сообщает rm удалять файлы в интерактивном режиме — это значит спрашивать перед удалением любого файла. Например:

$ rm -i file1 file2
rm: remove regular empty file `file1′? y
rm: remove regular empty file `file2′? y

В примере выше команда rm запрашивает подтверждение на удаление каждого из указанных файлов. В случае согласия, я должен был вводить «y» и нажать enter, дважды. Если бы я ввел «n», то файл бы остался цел. Или, если я сделал что-нибудь не так, я мог бы нажать Control-C и сбросить выполнение команды rm -i целиком — всяко до того, как это могло нанести какой-нибудь ущерб моей системе.

Если вы все еще учитесь пользоваться командой rm, то может быть полезным добавить при помощи вашего любимого текстового редактора следующую строку в ваш файл

/.bashrc, и затем выйти (logout) и войти (login) в систему вновь. После этого, всякий раз, когда вы наберете rm, оболочка bash преобразует ее автоматически в команду rm -i. Таким образом, rm будет всегда работать в интерактивном режиме:

rmdir

Для удаления директорий у вас имеется два варианта. Вы можете удалить все объекты внутри директории и затем воспользоваться rmdir для удаления самой директории:

$ mkdir mydir
$ touch mydir/file1
$ rm mydir/file1
$ rmdir mydir

Этот метод широко известен под названием «способ удаления директорий для лохов». Все реальные пацаны и админы-гуру съевшие пользователя собаку на этом деле, используют гораздо более удобную команду rm -rf, описанную далее.

Самый лучший способ удалить директорию состоит в использовании опций «рекурсивного принуждения» (recursive force) команды rm, чтобы приказать ей удалять указанную директорию, также как и объекты содержащиеся внутри:

Обычно, rm -rf является наиболее предпочтительным методом для удаления древа директорий. Будьте очень осторожны, когда пользуетесь rm -rf, так как ее мощь может быть использована по обе стороны: добра и зла. =)

Об авторах

Daniel Robbins

Дэниэль Роббинс — основатель сообщества Gentoo и создатель операционной системы Gentoo Linux. Дэниэль проживает в Нью-Мехико со свой женой Мэри и двумя энергичными дочерьми. Он также основатель и глава Funtoo, написал множество технических статей для IBM developerWorks, Intel Developer Services и C/C++ Users Journal.

Chris Houser

Крис Хаусер был сторонником UNIX c 1994 года, когда присоединился к команде администраторов университета Тэйлора (Индиана, США), где получил степень бакалавра в компьютерных науках и математике. После он работал во множестве областей, включая веб-приложения, редактирование видео, драйвера для UNIX и криптографическую защиту. В настоящий момент работает в Sentry Data Systems. Крис также сделал вклад во множество свободных проектов, таких как Gentoo Linux и Clojure, стал соавтором книги The Joy of Clojure.

Aron Griffis

Эйрон Гриффис живет на территории Бостона, где провел последнее десятилетие работая в Hewlett-Packard над такими проектами, как сетевые UNIX-драйвера для Tru64, сертификация безопасности Linux, Xen и KVM виртуализация, и самое последнее — платформа HP ePrint. В свободное от программирования время Эйрон предпочитает размыщлять над проблемами программирования катаясь на своем велосипеде, жонглируя битами, или болея за бостонскую профессиональную бейсбольную команду «Красные Носки».

Источник

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