Linux ln – How to Create a Symbolic Link in Linux [Example Bash Command]
A symlink (symbolic) is a type of file that points to other files or directories (folders) in Linux.
You can create a symlink (symbolic) by using the ln command in the command line.
Symbolic links are useful because they act as shortcuts to a file or directory.
In this article, I will go over how to use the ln command to create a symlink to a file or directory.
What is the difference between soft and hard links in Linux?
A soft link or symbolic link will point to the original file on your system. A hard link will create a copy of the file.
Soft links can point to other files or directories on a different file system, whereas hard links cannot.
How to create a symlink to a file
You can find the command line using the Terminal application on Mac or using the Command Prompt on Windows.
Here is the basic syntax for creating a symlink to a file in your terminal.
You use the ln command to create the links for the files and the -s option to specify that this will be a symbolic link. If you omit the -s option, then a hard link will be created instead.
The existing_source_file represents the file on your computer that you want to create the symbolic link for.
The optional_symbolic_link parameter is the name of the symbolic link you want to create. If omitted, then the system will create a new link for you in the current directory you are in.
Let’s take a look at an example to better understand how this works.
On my Desktop I have a file called example_fcc_file.txt .
I will need to first open up my terminal, and then make sure I am in the Desktop directory. I can run the command cd Desktop to navigate to my Desktop.
After running that command, you should see you are now in the Desktop.
I can then use the ln command to create a new symbolic link called fcc_link.txt .
When you run that command in the terminal, you will notice that nothing was returned. That is because when the ln command is successful, there will be no output and it will return zero.
To check that your symbolic link was successful, you can use the ls command. The ls command will list information about files and the -l flag represents the symbolic link.
When you run that command, you should see this type of result in the terminal.
The fcc_link.txt -> example_fcc_file.txt portion of the output shows you that the symbolic link is pointing to the file called example_fcc_file.txt .
You should also see that new symbolic link show up in your directory.
How to create a symbolic link to a directory
In this example, we want to create a symbolic link called my_music that will point to my Music folder in the home directory of my computer.
First, make sure you are in the home directory. You can run cd to get back to your home directory in the command line.
You can then use the ln command to create a symlink to the Music directory.
If successful, you should see it in the home directory.
How to remove a symbolic link
To remove symlink you can either use the unlink or rm command.
If we wanted to remove the fcc_link.txt symlink we created earlier, then we can use either of these commands:
Now we should see that the symlink was removed from our directory.
How to overwrite symlinks
If we try to create a new symlink called fcc_link.txt , then it will result in an error because it is already being used and pointing to another file.
You can overwrite this error by using the force ( -f ) option.
How to learn more about the ln command
If you want to learn more about the ln command, then you can read about it in the man pages (manual for using Linux commands).
Run man ln in your terminal and you should see the man pages for the ln command.
Conclusion
A symlink (symbolic) is a type of file that points to other files or directories (folders) in Linux. You can create a symlink (symbolic) by using the ln command in the command line.
Symbolic links are useful because they act as shortcuts to a file or directory.
Here is the basic syntax for creating a symlink to a file using the terminal:
Here is the basic syntax for creating a symlink to a directory using the terminal:
To remove symlink you can either use the unlink or rm command:
If you need to remove a symlink then you can use this command:
I hoped you enjoyed this article on symbolic links and best of luck on your programming journey.
Основы 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. Нам следует набрать:
Либо, альтернативный вариант:
Как вы видите, обе символические ссылки указывают на одну директорию. Однако, если наша вторая символьная ссылка когда-нибудь будет перемещена в другую директорию, то она может «поломаться» из-за относительности пути:
$ 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 будет всегда работать в интерактивном режиме:
alias rm=»rm -i»
rmdir
Для удаления директорий у вас имеется два варианта. Вы можете удалить все объекты внутри директории и затем воспользоваться rmdir для удаления самой директории:
$ mkdir mydir
$ touch mydir/file1
$ rm mydir/file1
$ rmdir mydir
Этот метод широко известен под названием «способ удаления директорий для лохов». Все реальные пацаны и админы-гуру съевшие пользователя собаку на этом деле, используют гораздо более удобную команду rm -rf, описанную далее.
Самый лучший способ удалить директорию состоит в использовании опций «рекурсивного принуждения» (recursive force) команды rm, чтобы приказать ей удалять указанную директорию, также как и объекты содержащиеся внутри:
$ rm -rf mydir
Обычно, 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. В свободное от программирования время Эйрон предпочитает размыщлять над проблемами программирования катаясь на своем велосипеде, жонглируя битами, или болея за бостонскую профессиональную бейсбольную команду «Красные Носки».
Символические и жесткие ссылки 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.
Теперь удалите исходный файл и посмотрите что будет:
Вы получите ошибку, что такого файла не существует, потому что мы действительно удалили исходный файл. Если вы удалите ссылку, то исходный файл останется на месте.
Создание жестких ссылок
Снова создайте файл source с произвольным текстом:
echo «текст текст текст текст» > source
$ cat source
Теперь создадим жесткую ссылку Linux. Для этого достаточно вызвать утилиту без параметров:
ln source hardlink
Посмотрите содержимое файла:
Данные те же самые, а если мы посмотрим вывод утилиты ls, то увидим что inode и права доступа тоже совпадают:
Если для одного из файлов поменять разрешения, то они изменяться и у другого. Теперь удалите исходный файл:
Затем посмотрите содержимое:
Как видите, ничего не произошло и ссылка по-прежнему указывает на нужный участок диска, это главное отличие жесткой ссылки от символической. Мы можем сделать вывод, что жесткая ссылка linux это обычный файл. Каждый файл имеет как минимум одну ссылку, но для некоторых мы можем создать несколько ссылок.
Выводы
Это все, что вам было необходимо знать про символические и жесткие ссылки linux. Надеюсь, вы получили общее представление об этих возможностях файловой системы и сможете использовать их для решения своих задач.
На завершение видео про ссылки в Linux:
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
Command Line Basics: Symbolic Links
Symbolic links allow you to link files and directories to other files and directories. They go by many names including symlinks, shell links, soft links, shortcuts, and aliases. From the user’s perspective, symbolic links are very similar to normal files and directories. However, when you interact with them, they will actually interact with the target at the other end. Think of them like wormholes for your file system.
This guide provides an overview of what symbolic links are and how to to create them from a Linux command line using the ln command.
Prerequisites
To follow along with this guide, you will need access to a computer running a Linux-based operating system. This can either be a virtual private server which you’ve connected to with SSH or your local machine. Note that this tutorial was validated using a Linux server running Ubuntu 20.04, but the examples given should work on a computer running any version of any Linux distribution.
If you plan to use a remote server to follow this guide, we encourage you to first complete our Initial Server Setup guide. Doing so will set you up with a secure server environment — including a non-root user with sudo privileges and a firewall configured with UFW — which you can use to build your Linux skills.
Setting Up Example Directories and Files
The system call necessary to create symbolic links tends to be readily available on Unix-like and POSIX-compliant operating systems. The command we’ll be using to create the links is the ln command.
You’re welcome to use existing files on your system to practice making symbolic links, but this section provides a few commands that will set up a practice environment you can use to follow along with this guide’s examples.
Begin by creating a couple directories within the /tmp/ directory. /tmp/ is a temporary directory, meaning that any files and directories within it will be deleted the next time the server boots up. This will be useful for the purposes of this guide, since you can create as many directories, files, and links as you’d like without having to worry about them clogging up your system later on.
The following mkdir command creates three directories at once. It creates a directory named symlinks/ within the /tmp/ directory, and two directories (one named one/ and another named two/ ) within symlinks/ :
Navigate into the new symlinks/ directory:
From there, create a couple sample files, one for both of the subdirectories within symlinks/ . The following command creates a file named one.txt within the one/ subdirectory whose only contents are a single line reading one :
Similarly, this command creates a file named two.txt within the two/ subdirectory whose only contents are a single line reading two :
If you were to run tree at this point to display the contents of the entire /tmp/symlinks directory and any nested subdirectories, its output would look like this:
Note: If tree isn’t installed on your machine by default, you can install it using your system’s package manager. On Ubuntu, for example, you can install it with apt :
With these sample documents in place, you’re ready to practice making symbolic links.
Understanding Hard Links
By default, the ln command will make hard links instead of symbolic, or soft, links.
Say you have a text file. If you make a symbolic link to that file, the link is only a pointer to the original file. If you delete the original file, the link will be broken as it no longer has anything to point to.
A hard link is instead a mirror copy of an original file with the exact same contents. Like symbolic links, if you edit the contents of the original file those changes will be reflected in the hard link. If you delete the original file, though, the hard link will still work, and you can view and edit it as you would a normal copy of the original file.
Hard links serve their purpose in the world, but they should be avoided entirely in some cases. For instance, you should avoid using hard links when linking inside of a git repository as they can cause confusion.
To ensure that you’re creating symbolic links, you can pass the -s or —symbolic option to the ln command.
Note: Because symbolic links are typically used more frequently than hard links, some may find it beneficial to alias ln to ln -s :
This may save only a few keystrokes, but if you find yourself making a lot of symbolic links this could add up significantly.
Working with Symbolic Links
As mentioned previously, symbolic linking is essentially like creating a file that contains the target’s filename and path. Because a symbolic link is just a reference to the original file, any changes that are made to the original will be immediately available in the symbolic link.
One potential use for symbolic links is to create local directories in a user’s home directory pointing to files being synchronized to an external application, like Dropbox. Another might be to create a symbolic link that points to the latest build of a project that resides in a dynamically-named directory.
Using the example files and directories from the first section, go ahead and try creating a symbolic link named three that points to the one directory you created previously:
Now you should have 3 directories, one of which is pointing back to another. To get a more detailed overview of the current directory structure, you can use the ls command to print the contents of the current working directory:
There are now three directories within the symlinks/ directory. Depending on your system, it may signify that three is in fact a symbolic link. This is sometimes done by rendering the name of the link in a different color, or appending it with an @ symbol.
For even greater detail, you can pass the -l argument to ls to determine where the symbolic link is actually pointing:
Notice that the three link is pointing to the one directory as expected. Also, it begins with an l , which indicates it’s a link. The other two begin with d , meaning that they are regular directories.
Symbolic links can also contain symbolic links. As an example, link the one.txt file from three to the two directory:
You should now have a file named one.txt inside of the two directory. You can check with the following ls command:
Depending on your terminal configuration, the link (highlighted in this example output) may be rendered in red text, indicating a broken link. Although the link was created, the way this example specified the path was relative. The link is broken because the two directory doesn’t contain a three directory with the one.txt file in it.
Fortunately, you can remedy this situation by telling ln to create the symbolic link relative to the link location using the -r or —relative argument.
Even with the -r flag, though, you won’t be able to fix the broken symbolic link. The reason for this is the symbolic link already exists, and you won’t be able to overwrite it without including the -f or —force argument as well:
With that, you now have two/one.txt which was linked to three/one.txt which is a link to one/one.txt .
Nesting symbolic links like this can quickly get confusing, but many applications are equipped to make such linking structures more understandable. For instance, if you were to run the tree command, the link target being shown is actually that of the original file location and not the link itself:
Now that things are linked up nicely, you can begin exploring how symbolic links work with files by altering the contents of these sample files.
To get a sense of what your files contain, run the following cat command to print the contents of the one.txt file in each of the three directories you’ve created in this guide:
Next, update the contents of the original one.txt file from the one/ directory:
Then check the contents of each file again:
As this output indicates, any changes you make to the original file will be reflected in any of its symbolic links.
Now try out the reverse. Run the following command to change the contents of one of the symbolic links. This example changes the contents of the one.txt file within the three/ directory:
Then check the contents of each file once again:
Because the symbolic link you changed is just a pointer to another file, any change you make to the link will be immediately reflected in the original file as well as any of its other symbolic links.
Conclusion
Symbolic links can be incredibly useful, but they do have certain limitations. Keep in mind that if you were to move or delete the original file or directory, all of your existing symbolic links pointed to it will become broken. There’s no automatic updating in that scenario. As long as you’re careful, though, you can find many uses for symbolic links as you continue working with the command line.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.