- How to Create Symbolic Links in Linux
- What are Linux Symbolic Links
- How to Create Symbolic Links in Linux?
- Create Symbolik Link in Linux for Files
- Create Symbolic Link in Linux for Folders
- How to Change or Remove Symbolic Link in Linux?
- Wrapping up
- linux-notes.org
- Создание ссылок (symlink) в Unix/Linux
- What is Symbolic Links in Linux? How to Create Symbolic Links?
- What is Symbolic link in Linux and why is it used?
- How to create a symbolic link in Linux
- Things to keep in mind about symbolic links
- Changes made to link are reflected in the original file
- Does it link to a file or a directory? You may not know!
- You can create links to non-existent file or directory
- The symbolic links are created with 777 permission but it means nothing
- You can link to a link of a link aka chained symbolic link
- Ln Command: How to Create Symbolic Links in Linux
- Ln Command to Create Symbolic Links
- Create a Symbolic Link to Linux Directory
- Force Overwrite Symbolic Links
- Deleting or Removing Links
- Soft Links vs Hard Links
- Soft (Symbolic) Links
- Hard Links
How to Create Symbolic Links in Linux
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.
What are Linux 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.
How to Create Symbolic Links in Linux?
Let’s look at how you can create file and folder links in Linux:
Create Symbolik Link in Linux for Files
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.
Create Symbolic Link in Linux for Folders
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 |
How to Change or Remove Symbolic Link in Linux?
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.
Источник
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» завершена. Не сильно сложная тема, но очень полезная.
Источник
What is Symbolic Links in Linux? How to Create Symbolic Links?
What is Symbolic link in Linux and why is it used?
A symbolic link, also known as a symlink or a soft link, is a special type of file that simply points to another file or directory just like shortcuts in Windows. Creating symbolic link is like creating alias to an actual file.
If you try to access the symbolic link, you actually access the target file to which the symlink points to. Changes performed on the content of the link file changes the content of the actual target file.
If you use the ls command with option -l, this is what a symbolic link looks like:
In most Linux distributions, the links are displayed in a different color than the rest of the entries so that you can distinguish the links from the regular files and directories.
Soft Link displayed in different color
Symbolic links offer a convenient way to organize and share files. They provide quick access to long and confusing directory paths. They are heavily used in linking libraries in Linux.
Now that you know a little about the symbolic links, let’s see how to create them.
How to create a symbolic link in Linux
To create a symbolic link to target file from link name, you can use the ln command with -s option like this:
The -s option is important here. It determines that the link is soft link. If you don’t use it, it will create a hard link. I’ll explain the difference between soft links and hard links in a different article.
Things to keep in mind about symbolic links
Symbolic links could be confusing at times therefore you should keep note of a few things.
Changes made to link are reflected in the original file
That’s the whole purpose of the links after all. You access the target file by accessing the link. You can make changes to the target file through the links. Let’s see with example.
I have a file prog.py in newdir/test_dir. It has the following attributes:
Now, I’ll create a soft link to this file in my present directory:
Here are the attributes of the newly created link:
Notice the l (it’s L, not one) at the beginning of the line? If you are familiar with the file permissions in Linux, you would know that the ‘l’ signifies link and thus it tells you that this file is actually a link. To refresh your memory, – means file, and d means directory.
Now if I use this link to change the content or the attributes, the same will be reflected in the target file. For example, I am using touch command on the soft link and you’ll notice that it changes the timestamp of the target file.
Does it link to a file or a directory? You may not know!
How would you know if the link points to file or a directory? You cannot know that until you follow the path and access the target file itself.
You can create links to non-existent file or directory
Yes, that’s totally possible. This is why you should be careful while creating soft links in Linux. The target file to which you are linking doesn’t need to exist. You won’t get any error or warning for creating link to a file/directory that does not exist.
You’ll get error only when you try to access the target file, either through the link or on its own. The ls command will still work though.
The symbolic links are created with 777 permission but it means nothing
Did you notice the file permission on the symbolic link? The symlinks are always created with 777 permission (rwxrwxrwx). For regular file, this would mean that anyone can access the file. But that’s not the case for the links.
If the file permissions on the links were treated as it is, any user could create a symlink to a secure file and access it freely. That would be a major security issue. Thankfully, that doesn’t happen. Because the permission on the target files matter, not the permission on links.
You may use the chmod command to change the permission on the link but it will change the permission of the linked file, not the link itself.
You can link to a link of a link aka chained symbolic link
You can make a symbolic link that points to another link and so on. This is called chained symbolic link. It’s better to avoid them as it creates more confusion.
Well, that’s it. I presume you have a better knowledge of the soft links now and you know how to create symbolic links in Linux. You may read about the symlinks command that can help you find broken symlinks in Linux and manage them easily.
If you have questions or suggestions, please leave a comment below.
Источник
Ln Command: How to Create Symbolic Links in Linux
Home » SysAdmin » Ln Command: How to Create Symbolic Links in Linux
A link creates a reference to a file or folder. Symbolic links are used in Linux for managing and collating files.
In this guide, learn how to use the ln command to create symbolic links in Linux.
- A system running Linux
- Access to a terminal window / command line (Activities >Search> type Terminal)
- (optional) A user account with sudo or root privileges (needed to access certain protected files and directories)
Ln Command to Create Symbolic Links
To use the ln command, open a terminal window and enter the command with the following format:
- By default, the ln command creates a hard link.
- Use the -s option to create a soft (symbolic) link.
- The -f option will force the command to overwrite a file that already exists.
- Source is the file or directory being linked to.
- Destination is the location to save the link – if this is left blank, the symlink is stored in the current working directory.
For example, create a symbolic link with:
This creates a symbolic link (link_file.txt) that points to the test_file.txt.
To verify whether the symlink has been created, use the ls command:
Create a Symbolic Link to Linux Directory
A symbolic link can refer to a directory. To create a symbolic link to a directory in Linux:
This example creates a symbolic link named stock_photos in the home (
/) directory. The link refers to the stock_photos directory on an external_drive.
Note: If the system has a connection to another computer, such as a corporate network or a remote server, symlinks can be linked to resources on those remote systems.
Force Overwrite Symbolic Links
You might receive an error message as displayed in the image below:
The error message means that there’s already a file in the destination named link_file.txt. Use the -f option to force the system to overwrite the destination link:
Note: Using the -f option will permanently delete the existing file.
Deleting or Removing Links
If the original file is moved, deleted, or becomes unavailable (such as a server going offline), the link will be unusable. To remove a symbolic link, use either the rm (remove) or unlink command:
Soft Links vs Hard Links
The ln command can be used to create two different kinds of links:
- Soft links
- Hard links
Soft (Symbolic) Links
A soft link, sometimes called a symbolic link or symlink, points to the location or path of the original file. It works like a hyperlink on the internet.
Here are a few important aspects of a soft link:
- If the symbolic link file is deleted, the original data remains.
- If the original file is moved or deleted, the symbolic link won’t work.
- A soft link can refer to a file on a different file system.
- Soft links are often used to quickly access a frequently-used file without typing the whole location.
Hard Links
When a file is stored on a hard drive, several things happen:
- The data is physically written to the disk.
- A reference file, calledinode, is created to point to the location of the data.
- A filename is created to refer to the inode data.
A hard link works by creating another filename that refers to the inode data of the original file. In practice, this is similar to creating a copy of the file.
Here are a few important aspects of hard links:
- If the original file is deleted, the file data can still be accessed through other hard links.
- If the original file is moved, hard links still work.
- A hard link can only refer to a file on the same file system.
- The inode and file data are permanently deleted when the number of hard links is zero.
You should now have a solid understanding of hard and symbolic (soft) links, and how to work with them. Use the ln command to create links and verify using the ls command.
Источник