Символическая ссылка windows что это

Символическая ссылка (симлинк, символьная ссылка, 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 утилита для создания симлинков в windows

Синтаксис у утилиты
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

параметр групповой политики Create Symbolic Links

Создадим в каталоге 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”

пример использования mklink для создание символьных ссылок в windows

Теперь при переходе в каталог C:\PS\Downloads вы будете видеть содержимое каталога, на который он ссылается.

символическая ссылка на каталог в windows

Выведем содержимое каталога C:\PS:

Dir c:\ps

Как вы видите, в атрибутах некоторых файлов указано, что это symlink/simlinkd. Также указан объект, на который они ссылаются. В Windows File Explorer симлинки отображаются с иконками ярлыков, а в их свойствах можно посмотреть целевой объект на который они ссылаются. Dir вывести информацию о всех symlink в папке

Также можно создать символически ссылки в Windows 10 с помощью PowerShell (в этом примере я использую относительные пути, чтобы создать символическую ссылку):

New-Item -ItemType SymbolicLink -Path ".\test\tmpfiles" -Target "..\tmp\files"

создать SymbolicLink с помощью powershell

Можно создать символическую ссылку на сетевую папку на удаленном компьютере/сервере. Адрес сетевой папки нужно указывать в формате 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 query SymlinkEvaluation

Чтобы включить использование символических ссылок на удаленные ресурсы, выполните команды:

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:\
    — укажите имя диска, на котором нужно найти все символические ссылки (если вы не хотите сканировать весь диск, укажите путь к нужному каталогу)

вывести все симлинке на диске в windows

Также можно вывести список всех символических ссылок на диске с помощью PowerShell. Для этого нужно просканировать все каталоги и найти NTFS объекты с атрибутом ReparsePoint:

Get-ChildItem -Path C:\ -Force -Recurse -ErrorAction 'silentlycontinue' | Where { $_.Attributes -match "ReparsePoint"}

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.

picture1

Figure 1: SCM Tool Trends 2004-2016 (Source, Google)

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!

Figure 2: npm served 1.2Bn downloads in the first week of July 2016

Figure 2: npm served 1.2Bn downloads in the first week of July 2016

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

picture3

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):

picture4

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).

windows-hardlink-and-symlink-000.pngЖесткие и символические ссылки давно знакомы и активно используются Linux-администраторами, в то время как их Windows коллеги используют их гораздо реже, а некоторые вообще не знают о такой возможности. Тем не менее такая возможность в Windows существует и позволяет значительно упростить некоторые сценарии работы с папками и файлами. В данной статье мы рассмотрим все виды ссылок, доступные в среде ОС Windows, а также разные способы работы с ними, начиная от командной строки и заканчивая PowerShell.

Научиться настраивать MikroTik с нуля или систематизировать уже имеющиеся знания можно на углубленном курсе по администрированию MikroTik. Автор курса, сертифицированный тренер MikroTik Дмитрий Скоромнов, лично проверяет лабораторные работы и контролирует прогресс каждого своего студента. В три раза больше информации, чем в вендорской программе MTCNA, более 20 часов практики и доступ навсегда.

Жесткие ссылки (HardLink)

Жесткие ссылки представляют собой дополнительную запись в файловой таблице раздела для существующего файла. Таким образом жесткая ссылка ничем не отличается от исходного файла, но файл при этом не копируется физически и остается на диске в единственном экземпляре. При изменении файла по любой из жестких ссылок, остальные обновляются автоматически (что логично, так как файл один).

Мы можем переименовывать, копировать, перемещать (в пределах логического тома) ссылки — размер занимаемого места при этом не изменится. При удалении ссылок файл продолжает существовать до тех пор, пока не будет удалена последняя жесткая ссылка на него. Фактически отличить, где находится оригинальный файл, а где жесткая ссылка невозможно, по сути, файл на разделе это и есть жесткая ссылка.

Жесткая ссылка может существовать только в пределах логического тома, поддерживается файловыми системами NTFS и ReFS начиная со сборки 19536.

Для создания жесткой ссылки можно воспользоваться утилитой mklink:

mklink /H C:\Folder1\LinkFileName C:\Folder\FileName

Где ключ /H предписывает создать именно жесткую ссылку, далее следует путь к новому файлу и целевому файлу, на который мы делаем ссылку. Путь можно указывать как абсолютные, так и относительные, в имени создаваемого файла не забывайте указывать расширение.

windows-hardlink-and-symlink-001.pngСсылки можно создавать и при помощи PowerShell, для этого воспользуйтесь командой:

New-Item -ItemType HardLink -Path C:\Folder1\LinkFileName -Target C:\Folder\FileName

Команда другая, но принцип тот же самый: -ItemType — тип создаваемой ссылки, в нашем случае жесткая ссылка, -Path — путь к создаваемому файлу ссылки, -Target — файл на который мы делаем ссылку.

windows-hardlink-and-symlink-002.pngМожно ли сделать жесткую ссылку на директорию? Нет, только на файлы.

Вроде бы все понятно, но если внимательный читатель заглянет в свойства папки с жесткой ссылкой, то он увидит, что ее размер равен исходному файлу, если сделаем в ней еще одну жесткую ссылку — двум исходным файлам. Как так? Не стоит переживать, все нормально. Для операционной системы жесткая ссылка ничем не отличается от обычного файла и при подсчете свободного места учитывается размер каждой ссылки, но на самом деле на диске хранится единственная копия. В этом можно убедиться, если одновременно с созданием жестких ссылок контролировать свободное место на диске.

При желании мы можем провернуть даже такой фокус:

windows-hardlink-and-symlink-003.pngКакой вывод можно сделать из того, что мы увидели и где нам могут пригодиться жесткие ссылки? Прежде всего для предоставления пользователям доступа к объемным архивам, образам или инсталляционным пакетам. Скажем у вас есть файловый сервер и несколько отделов, каждому из которых нужно предоставить доступ к одному и тому же большому файлу. При этом вы можете не бояться, что кто-то удалит файл, он удалит его только у себя в директории, для остальных пользователей он останется доступен.

Но при этом надо очень внимательно относиться к вопросу одновременного редактирования файла, так как он существует в единственном экземпляре, но доступен по множеству ссылок в этом сценарии могут возникнуть самые разные коллизии.

Точки соединения (Junction)

Очень старая технология, поддерживаемая еще начиная с Windows 2000, позволяет сделать один из каталогов псевдонимом другого каталога. Чем-то напоминает символические ссылки, но в крайне упрощенном варианте. В качестве цели можно использовать только локальные папки, но при этом нет ограничения по размещению их на одном томе. Т.е. целевая папка может находиться на диске C:, а точка соединения для нее на диске D: и все будет работать. Точки соединения поддерживаются файловыми системами NTFS и ReFS.

Для создания точки соединения можно использовать mklink:

mklink /J D:\LinkFolder C:\Folder

Ключ /J указывает на создание точки соединения, далее следует папка каталога-псевдонима и папка целевого каталога. При любом изменении целевого каталога (перемещение, переименование, удаление) точка соединения перестает работать.

Обратите внимание, что данная папка в проводнике отображается как ярлык, а выводе команды dir как точка соединения.

windows-hardlink-and-symlink-004.png

Это же действие в PowerShell:

New-Item -ItemType Junction -Path D:\LinkFolder -Target C:\Folder

Комментировать здесь особо нечего, краткость не входит в число добродетелей PowerShell, но не оставляет места догадкам, все просто и понятно.

Зачем сейчас нужны точки соединения? После появления в NT 6.0 настоящих символических ссылок не нужны, но вы можете встретиться с ними как в устаревших системах, так и в современных, где они могут присутствовать в виде наследия. Поэтому знать о них и уметь с ними работать современному администратору надо.

Символические ссылки (SymbolicLink)

Пожалуй, самый популярный вид связи, позволяет создавать множество псевдонимов для файлов или каталогов размещая их на любых поддерживаемых локальных файловых системах. В качестве цели могут быть использованы как локальные, так и сетевые объекты. При создании символической ссылки можно использовать как абсолютные, так и относительные пути. Но в последнем случае вы не можете перемещать ссылку — она перестанет работать. Символические ссылки поддерживаются начиная с NT 6.0 (Vista и Server 2008) и работают с файловыми системами NTFS и ReFS.

Для создания символических ссылок можно использовать mklink, без параметров она создает симлинк для файла:

mklink  C:\Folder1\LinkFileName C:\Folder\FileName

При создании ссылки не забываем указать расширения для файла. Как и в случае с точкой соединения символическая ссылка отображается в виде ярлыка и обозначается в выводе команды dir:

windows-hardlink-and-symlink-005.pngДля создания символической ссылки на директорию добавьте ключ /D:

mklink /D D:\LinkFolder C:\Folder

В PowerShell все проще, тип объекта будет определен автоматически:

New-Item -ItemType SymbolicLink -Path C:\Folder1\LinkFileName -Target C:\Folder\FileName

Если в качестве цели указан файл — будет создана ссылка на файл, каталог — ссылка на каталог.

При переименовании, перемещении или удалении исходного файла или каталога все символические ссылки работать перестанут:

windows-hardlink-and-symlink-006.pngПри копировании символической ссылки за пределы локального тома будет скопирован исходный файл, даже если целевой том поддерживает работу со ссылками, но это не мешает создать новую ссылку на другом томе.

Научиться настраивать MikroTik с нуля или систематизировать уже имеющиеся знания можно на углубленном курсе по администрированию MikroTik. Автор курса, сертифицированный тренер MikroTik Дмитрий Скоромнов, лично проверяет лабораторные работы и контролирует прогресс каждого своего студента. В три раза больше информации, чем в вендорской программе MTCNA, более 20 часов практики и доступ навсегда.

In computing, a symbolic link (also symlink or soft link) is a file whose purpose is to point to a file or directory (called the «target») by specifying a path thereto.[1]

Symbolic links are supported by POSIX and by most Unix-like operating systems, such as FreeBSD, Linux, and macOS. Limited support also exists in Windows 7 and Windows Vista, and to some degree in Windows 2000 and Windows XP in the form of shortcut files. CTSS on IBM 7090 had files linked by name in 1963.[2][3][4] By 1978 minicomputer operating systems from DEC, and in Data General’s RDOS included symbolic links.

Overview[edit]

A symbolic link contains a text string that is automatically interpreted and followed by the operating system as a path to another file or directory. This other file or directory is called the «target». The symbolic link is a second file that exists independently of its target. If a symbolic link is deleted, its target remains unaffected. If a symbolic link points to a target, and sometime later that target is moved, renamed or deleted, the symbolic link is not automatically updated or deleted, but continues to exist and still points to the old target, now a non-existing location or file. Symbolic links pointing to moved or non-existing targets are sometimes called broken, orphaned, dead, or dangling.

Symbolic links are different from hard links. Hard links do not link paths on different volumes or file systems, whereas symbolic links may point to any file or directory irrespective of the volumes on which the link and target reside.
Hard links always refer to an existing file, whereas symbolic links may contain an arbitrary path that does not point to anything.

Symbolic links operate transparently for many operations: programs that read or write to files named by a symbolic link will behave as if operating directly on the target file. However, they have the effect of changing an otherwise hierarchic filesystem from a tree into a directed graph, which can have consequences for such simple operations as determining the current directory of a process. Even the Unix standard for navigating to a directory’s parent directory no longer works reliably in the face of symlinks. Some shells heuristically try to uphold the illusion of a tree-shaped hierarchy, but when they do, this causes them to produce different results from other programs that manipulate pathnames without such heuristic, relying on the operating system instead.[5]
Programs that need to handle symbolic links specially (e.g., shells and backup utilities) thus need to identify and manipulate them directly.

Some Unix as well as Linux distributions use symbolic links extensively in an effort to reorder the file system hierarchy. This is accomplished with several mechanisms, such as variant, context-dependent symbolic links. This offers the opportunity to create a more intuitive or application-specific directory tree and to reorganize the system without having to redesign the core set of system functions and utilities.

POSIX and Unix-like operating systems[edit]

In POSIX-compliant operating systems, symbolic links are created with the symlink[6] system call. The ln shell command normally uses the link[7] system call, which creates a hard link. When the ln -s flag is specified, the symlink() system call is used instead, creating a symbolic link. Symlinks were introduced in 1982 in 4.1a BSD Unix from U.C. Berkeley.[8]

The following command creates a symbolic link at the command-line interface (shell):

 ln -s target_path link_path

target_path is the relative or absolute path to which the symbolic link should point. Usually the target will exist, although symbolic links may be created to non-existent targets. link_path is the path of the symbolic link.

After creating the symbolic link, some operations can be used to treat it as an alias for the target. However, the lstat,[9] lchown[10] and readlink[11] operations are unique to symbolic links and do not apply to the target; by using those system calls, programs that examine the file system (e.g., ls, find) can report on symbolic links (instead of their targets, if any). Because the rename and unlink system calls are coded to operate directly on symbolic links, file system management commands (e.g., rm, mv) affect the symbolic link itself (instead of being applied to the symbolic link target, if any). The rm (delete file) command removes the link itself, not the target file. Likewise, the mv command moves or renames the link, not the target. The cp command has options that allow either the symbolic link or the target to be copied. Commands which read or write file contents will access the contents of the target file.

The POSIX directory listing application, ls, denotes symbolic links with an arrow after the name, pointing to the name of the target file (see following example), when the long directory list is requested (-l option). When a directory listing of a symbolic link that points to a directory is requested, only the link itself will be displayed. In order to obtain a listing of the linked directory, the path must include a trailing directory separator character (‘/’, slash).

Note: In the example below do not create «three» directory before creation of link in /tmp directory.

$ mkdir -p /tmp/one/two
$ echo "test_a" >/tmp/one/two/a
$ echo "test_b" >/tmp/one/two/b
$ cd /tmp/one/two
$ ls -l
-rw-r--r-- 1 user group 7 Jan 01 10:01 a
-rw-r--r-- 1 user group 7 Jan 01 10:01 b

$ cd /tmp
$ ln -s /tmp/one/two three
$ ls -l three
lrwxrwxrwx 1 user group 12 Jul 22 10:02 /tmp/three -> /tmp/one/two
$ ls -l three/
-rw-r--r-- 1 user group 7 Jan 01 10:01 a
-rw-r--r-- 1 user group 7 Jan 01 10:01 b

$ cd three
$ ls -l
-rw-r--r-- 1 user group 7 Jan 01 10:01 a
-rw-r--r-- 1 user group 7 Jan 01 10:01 b
$ cat a
test_a
$ cat /tmp/one/two/a
test_a
$ echo "test_c" >/tmp/one/two/a
$ cat /tmp/one/two/a
test_c
$ cat a
test_c

Storage of symbolic links[edit]

Early implementations of symbolic links stored the symbolic link information as data in regular files. The file contained the textual reference to the link’s target, and the file mode bits indicated that the type of the file is a symbolic link.

This method was slow and an inefficient use of disk-space on small systems. An improvement, called fast symlinks, allowed storage of the target path within the data structures used for storing file information on disk (inodes). This space normally stores a list of disk block addresses allocated to a file. Thus, symlinks with short target paths are accessed quickly. Systems with fast symlinks often fall back to using the original method if the target path exceeds the available inode space. The original style is retroactively termed a slow symlink. It is also used for disk compatibility with other or older versions of operating systems.

Although storing the link value inside the inode saves a disk block and a disk read, the operating system still needs to parse the path name in the link, which always requires reading additional inodes and generally requires reading other, and potentially many, directories, processing both the list of files and the inodes of each of them until it finds a match with the link’s path components. Only when a link points to a file in the same directory do «fast symlinks» provide significantly better performance than other symlinks.

The vast majority of POSIX-compliant implementations use fast symlinks. However, the POSIX standard does not require the entire set of file status information common to regular files to be implemented for symlinks. This allows implementations to use other solutions, such as storing symlink data in directory entries.

The file system permissions of a symbolic link are not used; the access modes of the target file are controlled by the target file’s own permissions. Some operating systems, such as FreeBSD, offer the ability to modify file permissions and filesystem attributes of a symbolic link, through lchmod[12] and lchflags[13] system calls respectively.

The reported size of a symlink is the number of characters in the path it points to.

Error handling[edit]

A traditional Unix filesystem has a tree structure,[14] however symbolic links allow it to contain loops.[5]

Microsoft Windows[edit]

NTFS symbolic link[edit]

NTFS 3.1 introduced support for symbolic links for any type of file. It was included with Windows XP, but was only enabled by default for kernel-mode apps. Windows Vista and later versions of Windows enabled support for symbolic links to user-mode applications. The mklink internal command of Windows Command Prompt can create symbolic links. Third-party drivers are required to enable support for NTFS symbolic links in Windows XP.[15] Unlike junction points, a symbolic link can also point to a file or remote Server Message Block (SMB) network path. Additionally, the NTFS symbolic link implementation provides full support for cross-filesystem links. However, the functionality enabling cross-host symbolic links requires that the remote system also support them.

Symbolic links are designed to aid in migration and application compatibility with POSIX operating systems. Microsoft aimed for Windows Vista’s symbolic links to «function just like UNIX links».[16] However, the implementation differs from Unix symbolic links in several ways. For example, Windows Vista users must manually indicate when creating a symbolic link whether it is a file or a directory.[17] Windows 7 and Vista support a maximum of 31 reparse points (and therefore symbolic links) for a given path (i.e. any given path can have at most 31 indirections before Windows gives up).[18] Only users with the new Create Symbolic Link privilege, which only administrators have by default, can create symbolic links.[19] If this is not the desired behavior, it must be changed in the Local Security Policy management console. Additionally, NTFS symbolic links to files are distinct from NTFS symbolic links to directories and therefore cannot be used interchangeably, unlike on POSIX where the same symbolic link can refer to either files or directories.

In Windows Vista and later, when the working directory path ends with a symbolic link, the current parent path reference, .., will refer to the parent directory of the symbolic link rather than that of its target. This behavior is also found at the shell level in at least some POSIX systems, including Linux, but never in accessing files and directories through operating system calls. For instance, bash builtin commands pwd and cd operate on the current logical directory. pwd is often used in scripts to determine the actual current working directory. When any path is used with a system call, any use of .. will use the actual filesystem parent of the directory containing the .. pseudo-directory entry. So, cd ..; cat something and cat ../something may return completely different results.

Examples[edit]

The following examples both create a symbolic link called «Downloads» at «E:\» that points to the Downloads folder in the current user’s profile.

  • The first example works in Windows Command Prompt only because mklink is an internal command.
mklink /D E:\Downloads %UserProfile%\Downloads
  • The second example works in PowerShell only because New-Item is an internal cmdlet.
New-Item -Path 'E:\Downloads' -ItemType 'SymbolicLink' -Value "$Env:UserProfile\Downloads"

NTFS junction points[edit]

The Windows 2000 version of NTFS introduced reparse points, which enabled, among other things, the use of Volume Mount Points and junction points. Junction points are for directories only, and moreover, local directories only; junction points to remote shares are unsupported.[20] The Windows 2000 and XP Resource Kits include a program called linkd to create junction points; a more powerful one named Junction was distributed by Sysinternals’ Mark Russinovich.

Not all standard applications support reparse points. Most noticeably, Backup suffers from this problem and will issue an error message 0x80070003[21] when the folders to be backed up contain a reparse point.

Shortcuts[edit]

Shortcuts, which are supported by the graphical file browsers of some operating systems, may resemble symbolic links but differ in a number of important ways. One difference is what type of software is able to follow them:

  • Symbolic links are automatically resolved by the file system. Any software program, upon accessing a symbolic link, will see the target instead, whether the program is aware of symbolic links or not.
  • Shortcuts are treated like ordinary files by the file system and by software programs that are not aware of them. Only software programs that understand shortcuts (such as the Windows shell and file browsers) treat them as references to other files.

The mechanisms also have different capabilities:

  • Microsoft Windows shortcuts normally refer to a destination by an absolute path (starting from the root directory), whereas POSIX symbolic links can refer to destinations via either an absolute or a relative path. The latter is useful if both the symlink and its target share some common ancestor path which is not known at creation (e.g., in an archive file that can be unpacked anywhere).
  • Microsoft Windows application shortcuts contain additional metadata that can be associated with the destination, whereas POSIX symbolic links are just strings that will be interpreted as absolute or relative pathnames.
  • Unlike symbolic links, Windows shortcuts maintain their references to their targets even when the target is moved or renamed. Windows domain clients may subscribe to a Windows service called Distributed Link Tracking[dead link] to track the changes in files and folders to which they are interested. The service maintains the integrity of shortcuts, even when files and folders are moved across the network.[22] Additionally, in Windows 9x and later, Windows shell tries to find the target of a broken shortcut before proposing to delete it.

Folder shortcuts[edit]

Almost like shortcuts, but transparent to the Windows shell.[23] They are implemented as ordinary folders (which need to have the read only and/or system attribute[24]) containing a shortcut named target.lnk which refers to the target and a (hidden) desktop.ini with (at least) the following contents:

 [.ShellClassInfo]
 CLSID2={0AFACED1-E828-11D1-9187-B532F1E9575D}

Folder shortcuts are created and used from the Windows shell in the network neighborhood for example.

Shell objects[edit]

The shell objects[25] or shell folders are defined in the Windows registry and can be used to implement a sort of symbolic link too. Like folder shortcuts, they are transparent to the Windows shell.

A minimal implementation is (the CLSID {00000000-0000-0000-0000-000000000000} is used as a placeholder):

 [HKEY_CLASSES_ROOT\CLSID\{00000000-0000-0000-0000-000000000000}]
 @="display name"
 [HKEY_CLASSES_ROOT\CLSID\{00000000-0000-0000-0000-000000000000}\DefaultIcon]
 @="..." ; path to icon
 [HKEY_CLASSES_ROOT\CLSID\{00000000-0000-0000-0000-000000000000}\InProcServer32]
 @="%SystemRoot%\\System32\\ShDocVw.Dll"
 "ThreadingModel"="Apartment"
 [HKEY_CLASSES_ROOT\CLSID\{00000000-0000-0000-0000-000000000000}\Instance]
 "CLSID"="{0AFACED1-E828-11D1-9187-B532F1E9575D}"
 [HKEY_CLASSES_ROOT\CLSID\{00000000-0000-0000-0000-000000000000}\Instance\InitPropertyBag]
 "Attributes"=hex:15,00,00,00
 "Target"="..." ; absolute (WITHOUT "TargetKnownFolder" or "TargetSpecialFolder" only)
                ; or relative path to target
 "TargetKnownFolder"="{guidguid-guid-guid-guid-guidguidguid}" ; GUID of target folder, Windows Vista and later
 "TargetSpecialFolder"="0x00xy" ; CSIDL of target
 [HKEY_CLASSES_ROOT\CLSID\{00000000-0000-0000-0000-000000000000}\ShellFolder]
 "Attributes"=hex:00,00,00,00

The My Documents folder on the Desktop as well as the Fonts and the Administrative Tools folders in the Control Panel are examples of shell objects redirected to file-system folders.

Cygwin symbolic links[edit]

Cygwin simulates POSIX-compliant symbolic links in the Microsoft Windows file system. It uses identical programming and user utility interfaces as Unix (see above), but creates Windows shortcuts (.lnk files) with additional information used by Cygwin at the time of symlink resolution. Cygwin symlinks are compliant with the POSIX standard in terms of how they are resolved, and with Windows standards in terms of their on-disk representation.

Additionally, Cygwin can be set up to support native Windows symbolic links which can be used out of Cygwin without restrictions.[26] This requires:

  1. Changing the CYGWIN environment variable to contain winsymlinks:native;
  2. Running the Cygwin with elevated rights because Windows restricts the creation of symbolic links to privileged users

Some differences exist, however. Cygwin has no way to specify shortcut-related information – such as working directory or icon – as there is no place for such parameters in ln -s command. To create standard Microsoft .lnk files Cygwin provides the mkshortcut and readshortcut utilities.[27]

The Cygwin User’s Guide has more information on this topic.[26] MSYS2, which is based on Cygwin, has a similar set of winsymlinks settings but defaults to copying the files.[28]

Comparison of POSIX and Windows symbolic links[edit]

  1. ^ except when using special tools
  2. ^ On saving, becomes an absolute path
  3. ^ Supported on Windows Vista and later. The Windows implementation is not POSIX-compliant. Creating them requires the «create symbolic link» privilege (SeCreateSymbolicLinkPrivilege). By default a user account holds this privilege when it is either an administrator or has Developer Mode enabled (Windows 10 v1703 and later).[29]
  4. ^ POSIX permits hard links on folders but does not require them. Modern file systems tend to not support it.

Other implementations[edit]

Implementations of features similar to symbolic links.

Early MIT[edit]

MIT Compatible Time-Sharing System c. 1963 and Incompatible Timesharing System both have linked files where the name of the target file is specified in a directory entry.[2][3][4]

Amiga[edit]

The command creating symbolic links is makelink, which is also used for hard links. Internally the dos.library returns an error code indicating that a target is a soft link if you try to perform actions on it that are only legal for a file, and applications that wish to follow the symbolic link then needs to explicitly make a call to follow the link and retry the operation. The AmigaDOS shell will follow links automatically.

Mac OS[edit]

In Mac OS, applications or users can also employ aliases, which have the added feature of following the target, even if it is moved to another location on the same volume. This is not to be confused with the shell command alias.

OS/2[edit]

In the OS/2 operating system, symbolic links somewhat resemble shadows in the graphical Workplace Shell. However, shadows, due to the fully object-oriented System Object Model, are considerably more powerful and robust than a simple link. For example, shadows do not lose their capabilities when renamed or when either the object or subject of the link is relocated.[30]

Variable symbolic links[edit]

Symbolic links may be implemented in a context-dependent or variable fashion, such that the link points to varying targets depending on a configuration parameter, run-time parameter, or other instantaneous condition.

A variable or variant symbolic link is a symbolic link that has a variable name embedded in it. This allows some flexibility in filesystem order that is not possible with a standard symbolic link. Variables embedded in a symbolic link may include user and environment specific information.

Operating systems that make use of variant symbolic links include NetBSD, DragonFly BSD, Domain/OS.[31][32][5]
Tru64 uses a context dependent symbolic link where the context is the cluster member number.

Pyramid Technology’s OSx Operating System implemented conditional symbolic links which pointed to different locations depending on which universe a program was running in. The universes supported were AT&Ts’s SysV.3 and the Berkeley Software Distribution (BSD 4.3). For example: if the ps command was run in the att universe, then the symbolic link for the directory /bin would point to /.attbin and the program /.attbin/ps would be executed. Whereas if the ps command was run in the ucb universe, then /bin would point to /.ucbbin and /.ucbbin/ps would be executed. Similar Conditional Symbolic Links were also created for other directories such as /lib, /usr/lib, /usr/include.[33]

See also[edit]

  • Symlink race — a security-vulnerability caused by symbolic links
  • freedup — generates links between identical data automatically

References[edit]

  1. ^ Pathname resolution, POSIX.
  2. ^ a b Walden, David; Van Vleck, Tom, eds. (2011). «Compatible Time-Sharing System (1961-1973): Fiftieth Anniversary Commemorative Overview» (PDF). IEEE Computer Society. Retrieved February 20, 2022. As CTSS developed, we provided ways for users to share their files on disk, through «common files» and «linking,»
  3. ^ a b Crisman, Patricia A., ed. (December 31, 1969). «The Compatible Time-Sharing System, A Programmer’s Guide» (PDF). The M.I.T Computation Center. Retrieved March 10, 2022. U.F.D. entries that point to other U.F.D. entries instead of to the file itself
  4. ^ a b Corbato, F. J.; Daggett, M. M.; Daley, R. C.; Creasy, R. J.; Hellwig, J. D.; Orenstein, R. H.; Korn, L. K. (1963). «The Compatible Time-Sharing System A Programmer’s Guide» (PDF). MIT. Retrieved November 29, 2022. Link: The format is similar to Copy. The specified file is not copied
  5. ^ a b c Pike, Rob (2000). Lexical file names in Plan 9 or getting dot-dot right (PDF). Proc. USENIX Annual Tech. Conf.
  6. ^ symlink, symlinkat. IEEE Std 1003.1, 2013 Edition.
  7. ^ link, linkat. IEEE Std 1003.1, 2013 Edition.
  8. ^ Bill Joy; Sam Leffler. «Surviving with 4.1a bsd». Retrieved 8 September 2023. It also includes a few other features which you may find useful, such as symbolic links and an improved group scheme.
  9. ^ fstatat, lstat, stat — get file status IEEE Std 1003.1, 2013 Edition.
  10. ^ lchown — change the owner and group of a symbolic link IEEE Std 1003.1, 2013 Edition.
  11. ^ readlink, readlinkat — read the contents of a symbolic link IEEE Std 1003.1, 2013 Edition.
  12. ^ «lchmod(2)». Manual pages for FreeBSD 11.
  13. ^ «lchflags(2)». Manual pages for FreeBSD 11.
  14. ^ Ritchie, D.M.; Thompson, K. (July 1978). «The UNIX Time-Sharing System». Bell System Tech. J. 57 (6): 1905–1929. CiteSeerX 10.1.1.112.595. doi:10.1002/j.1538-7305.1978.tb02136.x.
  15. ^ «Link Shell Extension website». Link Shell Extension website.
  16. ^ Symbolic Links, MSDN Library, Win32 and COM Development, 2008-01-18
  17. ^ «CreateSymbolicLinkA function (winbase.h)». MSDN.
  18. ^ Symbolic Link Programming Considerations, MSDN
  19. ^ Mark Russinovich: Inside the Windows Vista Kernel: Part 1 – File-based symbolic links, Microsoft Technet, February 2007.
  20. ^ «Sysinternals Junction documentation». microsoft.com. Retrieved 23 March 2018.
  21. ^ «Windows backup or restore errors 0x80070001, 0x81000037, or 0x80070003». support.microsoft.com.
  22. ^ «Distributed Link Tracking and Object Identifiers». Microsoft Developers Network. Microsoft Corporation. 20 March 2011. Retrieved 30 June 2011.
  23. ^ «Specifying a Namespace Extension’s Location». msdn.microsoft.com. Retrieved 23 March 2018.
  24. ^ «You cannot view or change the Read-only or the System attributes of folders in Windows Server 2003, in Windows XP, in Windows Vista or in Windows 7». support.microsoft.com. Retrieved 2021-07-08.
  25. ^ Creating Shell Extensions with Shell Instance Objects. msdn.microsoft.com
  26. ^ a b «Chapter 3. Using Cygwin». www.cygwin.com. Retrieved 2021-07-08.
  27. ^ «Using Cygwin effectively with Windows».
  28. ^ «Coreutils: ln —symbolic creates hard links (MSYS2-packages #249)». GitHub.
  29. ^ «Create symbolic links». Windows client documentation for IT Pros. Microsoft. 18 January 2023 – via Microsoft Learn.
  30. ^ Rojas, Miguel (16 December 2020). «Cómo ejecutar versiones de Python diferentes a las predeterminadas». manualestutor.com/. Retrieved 20 December 2020.
  31. ^ symlink(7) – NetBSD Miscellaneous Information Manual: magic symlinks.
  32. ^ Brooks Davis (2008). «Variant symbolic links for FreeBSD» (PDF).
  33. ^ Neil Brown (2016). «A case for variant symlinks». LWN.

External links[edit]

  • Q & A: The difference between hard and soft links as applied to Linux
  • Junction: maintain NTFS junction points (for Windows 2000 and above)
  • FSUtil Hardlink: Microsoft Technet page on using the command-line tool FSUtil to create hardlinks (for Windows 2000 and above)
  • Symbolic Drivers for Windows XP (in Japanese): file system drivers to enable Symbolic Links for Windows XP (also mirrored on Link Shell Extension site). Sources available.

Ниже мы разберем понятие жестких и символических ссылок в Windows, расскажем про их основное предназначение и ключевые отличия. Также Вы сможете научиться быстро создавать ссылки стандартными способами Windows или при помощи специального ПО.


Символические и жесткие ссылки в Windows

Содержание

  1. Символические ссылки
  2. Жесткие ссылки
  3. Как можно применить символические ссылки?
  4. Как упростить создание символических и жестких ссылок?

Символические ссылки

Символьные ссылки (также известный как «Мягкие ссылки» или «SymLink») представляют собой специальные объекты, в которых вместо информации и данных находится путь к конкретному файлу или каталогу на жестком диске компьютера.

Такой функционал имеет некоторые схожести с ярлыками, но в отличие от них, создается жесткая привязка символической ссылки к конкретному месту. Использование таких ссылок позволяет экономить место винчестере, а также получать своеобразную точку доступа к информации между различными файловыми системами, не заполняя носитель лишними копиями данных.

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

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

Жесткая ссылка или Hard Link имеет схожий функционал с символическими ссылками, но её ключевыми отличиями являются:

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

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

Как можно применить символические ссылки?

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

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

Для примера, попробуем создать символическую ссылку на программу для восстановления данных RS Partition Recovery, чтобы сэкономить место, перенести её на другой диск и в то же время не переустанавливать утилиту в корень папки на новом системном диске.

Важно! Функции символьных ссылок доступны с Windows Vista. Более старые версии ОС не поддерживают работу с ними, поскольку в их функционале присутствует возможность создания только жестких и мягких (ярлыков) ссылок.

Процесс создания символической ссылки выглядит следующим образом:

Шаг 1. Работа с символическими ссылками происходит через стандартную утилиту Windows – «Командная строка». Нажимаем сочетание клавиш Win+R и в открывшемся окне вводим команду «cmd».

«Символические и жесткие ссылки в Windows

Шаг 2. В открывшемся окне вводим команду «mklink», при помощи которой можно получить описание функционала и возможные действия с символическими ссылками.

«Символические и жесткие ссылки в Windows

Шаг 3. Ознакомившись с ключами, попробуем создать символическую ссылку на каталог «C:\Program Files (x86)\Recovery Software\RS Partition Recovery 2.8» для этого нам потребуется ввести следующую команду «mklink /j «D:\recoverymk» «C:\Program Files (x86)\Recovery Software\RS Partition Recovery 2.8″».

Разберем подробнее каждый из пунктов команды.

  • Mklink – основная команда связанная для создания символьных ссылок, её прописывают в начале.
  • /j – ключ для создания символьный ссылки для каталога. Для создания файла следует использовать ключ /d. Для жесткой ссылки ключ /h.
  • “D:\recoverymk” – путь куда будет сохранена символьная ссылка на каталог.
  • «C:\Program Files (x86)\Recovery Software\RS Partition Recovery 2.8» – источник, откуда была создана символьная ссылка.

В нашем случае успешное создание символьной ссылки выглядит следующим образом:

«Символические и жесткие ссылки в Windows

Проверяем созданную ссылку и её работу в том месте, которое было указано при создании. В нашем случае это «D:\recoverymk».

«Символические и жесткие ссылки в Windows

Пробуем запустить утилиту через символическую ссылку.

«Символические и жесткие ссылки в Windows

Программа RS Partition Recovery (как и любые другие программы, архивы, игры и т.д) успешно заработала через символическую ссылку.

Также продемонстрируем наглядное пособие по созданию символической ссылки на конкретный файл. Для примера создадим символьную ссылку архива «карты», который расположен на диске C.

Для этого вводим «mklink /d «D:\карты» «C:\карты»»

В данном случае каждая часть команды отвечает за следующее:

  • Mklink – основная команда для работы с ссылками.
  • /d – ключ для создания символьных ссылок на конкретные файлы.
  • «D:\карты» – место куда будет создана символьная ссылка.
  • «C:\карты» – источник (оригинал) файла.

«Символические и жесткие ссылки в Windows

Важно! Для выполнения действий необходимо открыть командную строку от имени администратора. В противном случае утилита выдаст ошибку «Недостаточно прав».

Как упростить создание символических и жестких ссылок?

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

Одной из самых популярных программ для быстрого создания ссылок из контекстного меню является Link Shell Extension.

Процесс создания символической ссылки с дополнительными утилитами выглядит следующим образом:

Шаг 1. Нажимаем ПКМ по нужному объекту и выбираем пункт «Запомнить источник ссылки».

«Символические и жесткие ссылки в Windows

Шаг 2. Переходим в любой каталог, куда будет помещена ссылка, нажимаем ПКМ по пустому месту и выбираем пункт «Поместить как», после чего следует выбрать «Жесткую ссылку» или «Символическую ссылку».

«Символические и жесткие ссылки в Windows

Независимо от метода создания, ссылки будут функционировать в штатном режиме.

  • Символическая ссылка windows на сетевую папку
  • Символ переноса строки в windows
  • Сеть доступ к интернету но интернета нет windows 10
  • Символ евро на клавиатуре как набрать windows 10
  • Сеть есть а интернет не работает windows