Символическая ссылка (симлинк, символьная ссылка, Symbolic link) это специальный файл на файловой системе, которые сам не содержит данных, а является по сути ярлыком, указывающим на какой-то другой объект (файл или папку). При обращении к симлику операционная система считает, что это оригинальный файл (папка) и работает с ними совершенно прозрачно.
Символические ссылки используются в Windows довольно часто для системных файлов и каталогов. Пользователь может их применять, когда нужно перенести часть “тяжелых” файлов на другой диск, но чтобы Windows считала, что файлы все еще находятся в исходном каталоге (например в ситуациях, когда нужно экономить место на SSD, перенеся некоторые каталоги на более медленный и емкий SSD, не нарушая работоспособности программ). Можно использовать симлинки на SMB файловом сервере, когда каталоги с разных LUN должны быть доступны через одну точку входа.
В Windows есть три типа файловых ссылок для NTFS томов: жесткие, мягкие (симлинки), точки соединения (Junction point).
- Hard Links (жесткие ссылки) – могут указывать только на локальный файл, но не на папку. Такой файл – это ссылка на другой файла на этом же диске без фактического дублирования самого файла. У него отображается такой же размер и свойства, как у целевого файла (но реальное место на диске он не занимает);
- Junction Points (Directory Hard Link, точка соединения) – могут указывать только на папку (на этом же или на другом разделе);
- Symbolic Links (мягкая ссылка, симлинк) – могут указывать на локальный файл, папку и сетевой каталог на удаленном компьютере (UNC), поддерживаются относительные пути.
В подавляющем большинстве случаев вам будет достаточно функционала symbolic link, как наиболее универсального средства создания ссылки на любой объект.
Как создать символическую ссылку в Windows?
Для создания символических и жестких ссылок в Windows можно использовать встроенную утилиты mklink или PowerShell.
Синтаксис у утилиты
mklink
простой. Чтобы создать символическую ссылку на файл, нужно указать имя ссылки и целевой объект, на который она должна указывать. Можно указать тип ссылки:
/D
— символьная (мягкая) ссылка на каталог,
/H
— жесткая ссылка,
/J
– точка соединения (Junction point).
Чтобы использовать mklinkдля создания символических ссылок нужно запустить командную строку с правами администратора. Иначе при запуске команды появится ошибка “
You do not have sufficient privilege to perform this operation
”.
Если вам нужно разрешить создавать символические ссылки обычным пользователям, нужно добавить группу пользователей в параметр групповой политики Create Symbolic Links (Computer configuration -> Window Settings -> Security settings -> User Rights Assignment в редакторе GPO). По умолчанию в этой политике добавлена только локальная группа «Administrators». Обновите локальные политики после изменения параметра: gpupdate /force
Создадим в каталоге C:\PS символическую ссылку на файл notepad.exe:
mklink C:\PS\note.exe c:\Windows\System32\notepad.exe
Должно появится сообщение:
symbolic link created for C:\PS\note.exe <<===>> c:\Windows\System32\notepad.exe
Теперь для запуска процесса notepad.exe можно использовать символическую ссылку note.exe.
Теперь создадим в этом каталоге симлинк на другой каталог на этом же диcке:
mklink /D “C:\PS\Downloads” “C:\Users\user\Downloads”
Теперь при переходе в каталог C:\PS\Downloads вы будете видеть содержимое каталога, на который он ссылается.
Выведем содержимое каталога C:\PS:
Dir c:\ps
Как вы видите, в атрибутах некоторых файлов указано, что это symlink/simlinkd. Также указан объект, на который они ссылаются. В Windows File Explorer симлинки отображаются с иконками ярлыков, а в их свойствах можно посмотреть целевой объект на который они ссылаются.
Также можно создать символически ссылки в Windows 10 с помощью PowerShell (в этом примере я использую относительные пути, чтобы создать символическую ссылку):
New-Item -ItemType SymbolicLink -Path ".\test\tmpfiles" -Target "..\tmp\files"
Можно создать символическую ссылку на сетевую папку на удаленном компьютере/сервере. Адрес сетевой папки нужно указывать в формате UNC. Следующий пример создаст симлинк на сетевой каталог на сервере:
mklink /D c:\ps\share \\mskfs01\Share
Например, подключим административную шару C$ с удаленного компьютера по IP адресу:
mklink /D c:\remotePC\server1 \\192.168.31.15\С$
Если при доступе к сетевой папке через симлинк, вы получили ошибку
The symbolic link cannot be followed because its type is disabled
проверьте разрешенные способы использования символических ссылок на вашем компьютере:
fsutil behavior query SymlinkEvaluation
Local to local symbolic links are enabled. Local to remote symbolic links are enabled. Remote to local symbolic links are disabled. Remote to remote symbolic links are disabled.
Чтобы включить использование символических ссылок на удаленные ресурсы, выполните команды:
fsutil behavior set SymlinkEvaluation R2R:1
fsutil behavior set SymlinkEvaluation R2L:1
Вы можете работать с символическими ссылками, как с обычными объектами файловой системы, можно переименовать, переносить или удалить их. Система автоматически изменит настройки таких симлинков, чтобы они указывали на верные целевые объекты.
Для удаления симлинков используются обычные команды, как и для удаления файлов:
Del c:\ps\note.exe
RD c:\ps\downloads
Как найти и вывести все символические ссылки на диске?
В Windows нет простых инструментов для просмотра и управления всеми симлинками на диске.
Вы можете вывести список всех символических ссылок на диске с помощью команды:
dir /AL /S C:\ | find "SYMLINK"
-
/A
– вывести файлы с атрибутом L (симлинк); -
/S
–выполнить команду рекурсивно для всех вложенных каталогов; -
C:\
— укажите имя диска, на котором нужно найти все символические ссылки (если вы не хотите сканировать весь диск, укажите путь к нужному каталогу)
Также можно вывести список всех символических ссылок на диске с помощью PowerShell. Для этого нужно просканировать все каталоги и найти NTFS объекты с атрибутом ReparsePoint:
Get-ChildItem -Path C:\ -Force -Recurse -ErrorAction 'silentlycontinue' | Where { $_.Attributes -match "ReparsePoint"}
Как создавать и удалять симлинки
Обновлено:
Опубликовано:
Используемые термины: Симлинк, Windows, Linux.
Windows
Linux
Проблемы и решения
Работы с символьными ссылками в Windows ведутся из командной строки.
Синтаксис
mklink <имя создаваемого симлинка> <на что ведет симлинк>
Симлинк на файл
mklink C:\Users\dmosk\Desktop\cmd.exe C:\Windows\system32\cmd.exe
* в данном примере на рабочем столе пользователя dmosk будет создан симлинк на файл cmd.exe.
Симлинк на директорию
mklink /D «C:\Users\dmosk\Desktop\Сетевая папка» \\dmosk.local\share
* в примере создается симлинк на сетевую папку \\dmosk.local\share
** так как в названии папки есть пробел, путь заключен в кавычки.
Для создания ссылки на папку доступен также ключ /J. Созданная таким образом ссылка будет по некоторым особенностям напоминать жесткую ссылку.
Удалить симлинк
В Windows его можно удалить в проводнике, как обычный файл или папку.
Или использовать командную строку.
Для папки:
rmdir «C:\Users\dmosk\Desktop\Сетевая папка»
Для файла:
del C:\Users\dmosk\Desktop\cmd.exe
Разрешить симлинки в Windows
Если при попытке перейти по символьной ссылке мы получим ошибку «Символическая ссылка не может быть загружена, так как ее тип отключен», открываем командную строку от администратора и вводим команду:
fsutil behavior set SymlinkEvaluation L2L:1 R2R:1 L2R:1 R2L:1
Если это не помогло, пробуем создать симлинк с ключом /J.
Linux и FreeBSD
Создание
Общий синтаксис
ln -s <на какой существующий объект будет вести> <создаваемый симлинк>
В системах на базе Linux (например, Ubuntu или CentOS) и FreeBSD симлинк для каталога и файла создаются одинаково:
ln -s /usr/share/nginx/html/index.php /home/dmosk/
ln -s /usr/share/nginx/html /home/dmosk/
* в первом примере создана символьная ссылка в домашней директории пользователя dmosk на файл index.php; во втором — на каталог /usr/share/nginx/html.
Удаление
Также используется одна команда:
rm /home/dmosk/index.php
Решение возможных проблем
При работе с симлинками мы можем сталкиваться с различными проблемами. Я рассмотрю те, с которыми приходилось сталкиваться мне.
ln: failed to create symbolic link … Function not implemented
При попытке создать симлинк мы можем получить ошибку Function not implemented, например:
ln: failed to create symbolic link ‘/etc/pve/nodes/pve/fullchain.pem’: Function not implemented
Причина: файловая система, на которой мы хотим создать файл не поддерживает симлинки. Посмотреть файловую систему подмонтированных разделов можно командой:
df -T
Решение: как правило, решения зависит от используемой файловой системы и ее драйвера. Но, обычно, решения у проблемы нет и нужно искать методы работы без использования символьных ссылок.
Did you know that Windows has supported symlinks since Vista? You can create them using the Windows Command Prompt.
🔗 What Are Symlinks?
Symbolic Links are basically advanced shortcuts that you create on the command line. Once created, Windows treats them just the same as if they were a normal folder.
For example, let’s say you have a program that needs its files at C:\MyProgram, but your C: Drive is dangerously low on space and you’d prefer to install that program on another drive, but it throws errors whenever you try to install it there. For the sake of this argument, we’re going to pretend that the installer will allow you to install to an existing directory — so that one way you could solve this problem would be to create a folder called D:\Stuff\MyProgram, and then create a symbolic link at C:\MyProgram which points to D:\Stuff\MyProgram. Now, once you’ve installed the program and launch it, when it tries to access C:\MyProgram, Windows will automatically redirect it to D:\Stuff\MyProgram, and your program will never know the difference!
This trick can be used for all sorts of things — including syncing any folder with programs such as Dropbox, Google Drive, and OneDrive.
There are two types of Symbolic Link — Hard
and Soft
. Soft Symbolic Links work similarly to a Windows Shortcut
. When you open a soft link to a folder, you will be redirected to the folder where the files are stored — which would probably not be suitable in our example above. A hard link, however, makes it appear as though the file or folder actually exists at the location of the symbolic link, and your applications won’t know the difference. I find myself using hard links as my default in most situations — but you can make up your own minds as to which you want to use where.
Windows uses slightly different terms here though. Instead of «hard link» and «soft link», Windows uses the terms «hard link» and «symbolic link». According to the Windows documentation, a «symbolic link» is exactly the same as a «soft link», and the mklink
command is what you need to use to create both kinds.
💻 Creating Symbolic Links with mklink
Firstly, open a Command Prompt in Administrator Mode:
- Click on the
Start
button - Scroll down to the
Windows System
folder in the Start Menu - Right-click on the
Command Prompt
shortcut and selectRun as Administrator
By default (without any additional options), the mklink
command will create a Symbolic Link (or «soft link») to a FILE. The command below creates a symbolic («soft») link at <link>
pointing to <target>
(you know NOT to type the angle brackets, right?):
To create a symbolic («soft») link to a target DIRECTORY, use the /D
option:
mklink /D <link> <target>
To create a «hard link» to a FILE, use:
mklink /H <link> <target>
And to create a «hard link» to a DIRECTORY (also known as a «directory junction»), use:
mklink /J <link> <target>
So, for example, if you wanted to create a directory junction («hard link» to a folder) at C:\LinkToFolder
which points at C:\Users\Username\TargetFolder
, you’d use the following command:
mklink /J C:\LinkToFolder C:\Users\Username\TargetFolder
If any of your paths have spaces in them, just put quotation marks around them:
mklink /J "C:\Link To Folder" "C:\Users\Username\Target Folder"
If you see the error message «You do not have sufficient privilege to perform this operation», it means that you haven’t launched the Command Prompt (or whatever it is you’ve used) as an Administrator before running the command … (which means you’re rushing things and need to slow down a little, because I DEFINITELY told you that in the first step!)
🚫 Deleting Windows Symlinks
The good news is that Windows Symlinks can be deleted just like any other file or folder from the Command Prompt, Windows Explorer, and any third-party package you might care to use.
Overview
Symlinks, or symbolic links, are “virtual” files or folders which reference a physical file or folder located elsewhere, and are an important feature built in to many operating systems, including Linux and Windows.
The Windows’ NTFS file system has supported symlinks since Windows Vista. However, it hasn’t been easy for Windows developers to create symlinks. In our efforts to continually improve the Windows Developer experience we’re fixing this!
Starting with Windows 10 Insiders build 14972, symlinks can be created without needing to elevate the console as administrator. This will allow developers, tools and projects, that previously struggled to work effectively on Windows due to symlink issues, to behave just as efficiently and reliably as they do on Linux or OSX.
Background
A symlink is essentially a pointer to a file or folder located elsewhere, consumes little space and is very fast to create (compared to copying a file and its contents).
Because of this, developers often replace duplicate copies of shared files/folders with symlinks referencing physical files/folders. Replacing redundant copies of files can save a great deal of physical disk space, and significantly reduce the time taken to copy/backup/deploy/clone projects.
In UNIX-compatible operating systems like Linux, FreeBSD, OSX, etc., symlinks can be created without restrictions.
However, for Windows users, due to Windows Vista’s security requirements, users needed local admin rights and, importantly, had to run mklink in a command-line console elevated as administrator to create/modify symlinks. This latter restriction resulted in symlinks being infrequently used by most Windows developers, and caused many modern cross-platform development tools to work less efficiently and reliably on Windows.
Now in Windows 10 Creators Update, a user (with admin rights) can first enable Developer Mode, and then any user on the machine can run the mklink command without elevating a command-line console.
What drove this change?
The availability and use of symlinks is a big deal to modern developers:
Many popular development tools like git and package managers like npm recognize and persist symlinks when creating repos or packages, respectively. When those repos or packages are then restored elsewhere, the symlinks are also restored, ensuring disk space (and the user’s time) isn’t wasted.
Git, for example, along with sites like GitHub, has become the main go-to-source code management tool used by most developers today.
The use of package managers in modern development has also exploded in recent years. For example, node package manager (npm) served ~400 million installs in the week of July 1st 2015, but served more than 1.2 billion installs just one year later – a 3x increase in just one year! In late June 2016, npm served more than 1.7 billion node packages in just seven days!
There are clear drivers demanding that Windows enables the ability to create symlinks to non-admin users:
- Modern development projects are increasingly portable across operating systems
- Modern development tools are symlink-aware, and many are optimized for symlinks
- Windows developers should enjoy a development environment that is at least the equal of others
How to use Symlinks
Symlinks are created either using the mklink command or the CreateSymbolicLink API
mklink
- There is no change in how to call mklink. For users who have Developer Mode enabled, the mklink command will now successfully create a symlink if the user is not running as an administrator.
CreateSymbolicLink
- To enable the new behavior when using the CreateSymbolicLink API, there is an additional dwFlags option you will need to set:
Value | Meaning |
SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE 0x2 |
Specify this flag to allow creation of symbolic links when the process is not elevated |
Example Use
In the example below:
- A subfolder folder called “animals” containing three files (cat.txt, dog.txt, and fish.txt)
- (green) The mklink command is executed to create a symlink called “pet.txt” pointing at the “animalsdog.txt” file
- (blue) When the contents of the current folder are listed, the symlink can be seen (yellow)
- (purple) When contents of pet.txt are queried, the content of the referenced file (“dog.txt”) is displayed
Once created, symlinks can be opened, loaded, deleted, etc., just like any other file. Here, the pet.txt symlink is being opened in Notepad (red):
How do I try it?
This new symlinks support first shipped in Windows 10 Insiders Build 14972, and will be formally delivered in Windows 10 Creators Update. We are also working with the owners of open-source community tools such as Git and npm so they know symlink improvements are coming and can make the necessary changes to better support symlinks on Windows.
We encourage you to take this new feature for a spin and be sure to let us know via the Windows 10 Feedback hub or on Twitter etc. (see below). Please sign up for the Windows Insiders program if you haven’t already to try out symlinks!
Neal, Yosef (@yosefdurr), Rich (@richturn_ms), and Gilles (@khouzam).
On Windows 11 and 10, you can use the built-in “mklink” command to create symbolic links (symlinks) for files and folders. A symbolic link acts as a shortcut (very different from the regular desktop shortcut), linking to a file or folder in one location while the actual content remains stored elsewhere. For example, you can create a symlink to sync any folder with OneDrive without moving the actual folder. Simply put, creating symlinks not only saves space but is an efficient way to manage files and directories across different drives or storage locations.
In this tutorial, I’ll show you how to create symbolic links (symlinks) for files and folders. Let’s get started.
Before You Begin
- You need administrator rights to create symlinks on Windows.
What Are Symbolic Links (symlinks) and Hard Links?
Before diving in and learning the steps to create symlinks, you need to understand the difference between symbolic links and hard links.
Symbolic Link (Symlink): A symlink is like a shortcut that points to another file or folder on your system. When you open a symlink, it takes you to the actual location of the original file or folder. Any changes made to the original file will appear in the symlink. If you delete the original file, the symlink becomes empty or unusable.
Hard link: A hard link acts like a copy of the original file but points to the same data on the disk. Hard links only work with files (not folders) and must be on the same drive as the original file. Changes to either the hard link or the original file reflect in the other, as both point to the same data. Unlike symlinks, deleting the original file does not break the hard link, as the data remains accessible through the link.
Create a Symlink for a File or Folder
- Right-click on the Start button.
- Select the “Terminal (Admin)” option.
- Click the down arrow on the title bar.
- Select the “Command Prompt” option.
- Run the following command to create a symlink to a folder.
mklink /D "C:\path\to\LinkFolder" "D:\path\to\ActualFolder"
- Run the following command to create a symlink to a file.
mklink "C:\path\to\LinkFile.txt" "D:\path\to\ActualFile.txt"
- With that, you’ve created the symlink for a file or folder on Windows.
Detailed Steps (With Screenshots)
First, open the terminal window with administrative privileges. To do that, right-click the Start button on the taskbar and choose the “Terminal (Admin)” option.
In the terminal window, open the Command Prompt tab by clicking the dropdown icon on the title bar and selecting the “Command Prompt” option.
Note: The below command doesn’t work in the PowerShell tab.
run the following commands to create a symlink.
In the command, replace the first path with the path where you want the symlink to appear and the second path with the actual file or folder path that you are linking.
- Symlink to a file
mklink "C:\path\to\LinkFile.txt" "D:\path\to\ActualFile.txt"
- Symlink to a folder
mklink /D "C:\path\to\LinkFolder" "D:\path\to\ActualFolder"
That is it. As soon as you execute the above command, Windows creates a symlink in the location and name of your choice. If you open the File Explorer and go to the drive/folder where you saved the symlink, you will see it immediately.
Wrapping Up — Creating Symlinks on Windows
As you can see, thanks to the built-in mklink command, you can easily create a symlink to any file or folder with just a single-line command. Do keep in mind that, any changes you make to the symlink will reflect in the original file or folder. Also, if you delete the original file or folder, the symlink will no longer work.
If you have any questions or need help, comment below. I’ll be happy to assist.