linux-notes.org
Хотелось бы рассказать как можно создавать ссылки (симлинки) в ОС Unix/Linux. В своей теме «Создание ссылок (symlink) в Unix/Linux» я на готовом примере покажу как это делается. Существуют несколько видов ссылок, и я расскажу в чем разница между ними.
Симлинк или мягкая ссылка представляет собой особый тип файла, который содержит ссылку на другой файл или каталог в виде абсолютного или относительного пути.
Жёсткой ссылкой — это структурная составляющая файла которая описывает его элемент каталога.
Создание ссылок (symlink) в Unix/Linux
В этом подразделе, я расскажу какие бывают симлинки и в чем они отличаются.
Мягкая ссылка (Soft link):
- Мягкие ссылки используют различные номера инод чем основные файлы.
- Мягкие ссылки становится полезными, если исходный файл был удален.
- Мягкие ссылки могут быть созданы из каталогов.
- Мягкая ссылка может быть создана на пересечении файловых систем.
Для того чтобы создать симлинк в линукс используется следующая команда:
И так, я создал симлинк 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):
- Жесткие ссылки использует тот же номер иноды что и основные файлы.
- Нельзя создать жесткие ссылки на каталоги.
- Жесткие ссылки не могут быть созданы на пересечении файловых систем.
- Жесткие ссылки всегда относится к источнику, даже если они перемещаются или удаляется.
Чтобы создать «жесткую ссылку», используйте:
Проверяем номер иноды:
Оба файла имеют одинаковые иноды (одинаковое количество индексных дескрипторов). Если нужно удалить «жесткую ссылку», то используйте команду:
Если вы удалите жесткую ссылку, ваши данные будут там. Если вы удалите /home/captain/linux-notes.org.txt то файл будет по-прежнему доступен через жесткую ссылку
Жесткие ссылки (Hardlink) vs Мягкие ссылки (Softlink) в UNIX/Linux
- Как я говорил ранее, жесткие ссылки не могут быть созданы для директорий.
- Жесткие ссылки не могут использоваться на пересечении границ файловых систем ( Нельзя создать сылку /tmp и примонтированную на /tmp ко 2-му HDD который смонтирован на/harddisk2).
- Символические ссылки (мягкие ссылки) ссылаются на символичный путь с указанием абстрактного расположение другого файла.
- Жесткие ссылки, ссылаются к определенному местоположению физических данных.
На этом, моя тема «Создание ссылок (symlink) в Unix/Linux» завершена. Не сильно сложная тема, но очень полезная.
How can I symlink a file in Linux? [closed]
Want to improve this question? Update the question so it’s on-topic for Stack Overflow.
I want to make a symbolic link in Linux. I have written this Bash command where the first path is the folder I want link into and the second path is the compiled source.
18 Answers 18
To create a new symlink (will fail if symlink exists already):
To create or update a symlink:
Where the -s makes it symbolic.
You can have a look at the man page here:
(Because an ASCII picture is worth a thousand characters.)
An arrow may be a helpful mnemonic, especially since that’s almost exactly how it looks in Emacs’ dired.
And big picture so you don’t get it confused with the Windows’ version
You could also look at these as
The from-here should not exist yet, it is to be created, while the to-here should already exist (IIRC).
(I always get mixed up on whether various commands and arguments should involve a pre-existing location, or one to be made.)
EDIT: It’s still sinking in slowly for me; I have another way I’ve written in my notes.
To the original question:
This will indeed create a symbolic link ( -s ) from the file/directory:
Here’s a few ways to help you remember:
First, there’s the man page for ln . You can access this via searching «man ln» in google, or just open a terminal window and type man ln and you’ll get the same information. The man page clearly states:
ln [OPTION]. [-T] TARGET LINK_NAME (1st form)
If having to search or read through a man page every time isn’t for you, maybe you’ll have an easier time remembering that all nix commands work the same way :
cp copies a file that currently exists (the first argument) to a new file (the second argument).
mv moves a file that currently exists (the first argument) to a new place (the second argument)
Likewise ln links a file that currently exists (the first argument) to a new link (the second argument) *
The final option I would like to suggest is you can create your own man pages that are easy to read and easy (for you) to find/remember. Just make a simple shell script that gives you the hint you need. For example ♦ :
In your .bash_aliases file you can place something like:
Then when you need it, from the command line just type cmds and you’ll get back the proper syntax in a way you can quickly read and understand it. You can make these functions as advanced as you’d like to get what what information you need, it’s up to you. You could even make them interactive so you just have to follow the prompts.. something like:
* — well obviously they can all take different parameters and do different things and can work on files as well as directories. but the premise is the same
♦ — examples using the bash shell
Ln Command in Linux (Create Symbolic Links)
Updated Sep 6, 2019
A symbolic link, also known as a symlink or soft link, is a special type of file that points to another file or directory.
In this guide, we will cover how to use the ln command to create symbolic links.
Links Types #
There are two types of links in Linux/UNIX systems:
- Hard links. You can think a hard link as an additional name for an existing file. Hard links are associating two or more file names with the same inode . You can create one or more hard links for a single file. Hard links cannot be created for directories and files on a different filesystem or partition.
- Soft links. A soft link is something like a shortcut in Windows. It is an indirect pointer to a file or directory. Unlike a hard link, a symbolic link can point to a file or a directory on a different filesystem or partition.
How to Use the ln Command #
ln is a command-line utility for creating links between files. By default, the ln command creates hard links. To create a symbolic link, use the -s ( —symbolic ) option.
The ln command syntax for creating symbolic links is as follows:
- If both the FILE and LINK are given, ln will create a link from the file specified as the first argument ( FILE ) to the file specified as the second argument ( LINK ).
- If only one file is given as an argument or the second argument is a dot ( . ), ln will create a link to that file in the current working directory . The name of the symlink will be the same as the name of the file it points to.
By default, on success, ln doesn’t produce any output and returns zero.
Creating Symlink To a File #
To create a symbolic link to a given file, open your terminal and type:
Replace source_file with the name of the existing file for which you want to create the symbolic link and symbolic_link with the name of the symbolic link.
The symbolic_link parameter is optional. If you do not specify the symbolic link, the ln command will create a new link in your current directory:
In the following example, we are creating a symbolic link named my_link.txt to a file named my_file.txt :
To verify that the symlink was successfully created, use the ls command:
The output will look something like this:
The l character is a file type flag that represents a symbolic link. The -> symbol shows the file the symlink points to.
Creating Symlinks To a Directory #
The command for creating a symbolic link to a directory is the same as when creating a symbolic link to a file. Specify the directory name as the first parameter and the symlink as the second parameter.
For example, if you want to create a symbolic link from the /mnt/my_drive/movies directory to the
/my_movies directory you would run:
Overwriting Symlinks #
If you try to create a symbolic link that already exists , the ln command will print an error message.
To overwrite the destination path of the symlink, use the -f ( —force ) option.
Removing Symlinks #
To delete/remove symbolic links use either the unlink or rm command.
The syntax of the unlink is very simple:
Removing a symbolic link using the rm command is the same as when removing a file:
No matter which command you use, when removing a symbolic link not append the / trailing slash at the end of its name.
If you delete or move the source file to a different location, the symbolic file will be left dangling (broken) and should be removed.
Conclusion #
To create a symbolic link is Linux use the ln command with the -s option.
For more information about the ln command, visit the ln man page or type man ln in your terminal.
If you have any questions or feedback, feel free to leave a comment.