So I created a symlink:
ln -s /location/to/link linkname
Now I want to change the location that the symlink links to. How do I do that? is there a way to do it without deleting it first?
asked Nov 13, 2009 at 5:22
1
You could create the new link with a different name, then move it to replace the old link.
ln -s /location/to/link linkname
Later
ln -s /location/to/link2 newlink
mv newlink linkname
If newlink and linkname are on the same physical device the mv should be atomic.
answered Nov 13, 2009 at 7:01
martin claytonmartin clayton
75.8k31 gold badges216 silver badges198 bronze badges
5
Try ln -sf new_destination linkname.
answered Nov 13, 2009 at 5:33
PhilPhil
4,6871 gold badge23 silver badges21 bronze badges
3
Just change the symlink target:
# ln -sfT /path/to/new/target linkname
This is an instant, atomic change.
answered Feb 18, 2015 at 5:08
Jake WilsonJake Wilson
86.9k93 gold badges250 silver badges358 bronze badges
2
If the symlink targets are directories, you need to add the -T flag to the mv command, otherwise it moves the new symlink in to the target directory of the old symlink.
Example of atomically switching a website to a new version:
Original setup — website is stored in www1 directory, vhost pointing at www symlink:
ln -s www1 www
Browse to website, see old version.
Put new website files in new www2 directory.
Set up new symlink to new website:
ln -s www_new www2
Move www symlink to directory of new website:
mv -T www_new www
Browse to website, see new version immediately.
answered Mar 26, 2013 at 17:44
ben_nuttallben_nuttall
84910 silver badges20 bronze badges
2
On OSX, the man page for ln says you can do it like this
ln -shf /location/to/link link name
From the man page:
The options are as follows:
-F If the target file already exists and is a directory, then remove it so that the link may occur. The -F
option should be used with either -f or -i options. If none is specified, -f is implied. The -F option is
a no-op unless -s option is specified.
-h If the target_file or target_dir is a symbolic link, do not follow it. This is most useful with the -f
option, to replace a symlink which may point to a directory.
-f If the target file already exists, then unlink it so that the link may occur. (The -f option overrides any
previous -i options.)
-i Cause ln to write a prompt to standard error if the target file exists. If the response from the standard
input begins with the character `y' or `Y', then unlink the target file so that the link may occur. Other-
wise, do not attempt the link. (The -i option overrides any previous -f options.)
-n Same as -h, for compatibility with other ln implementations.
-s Create a symbolic link.
-v Cause ln to be verbose, showing files as they are processed.
answered Feb 17, 2014 at 21:30
jschankjschank
5541 gold badge5 silver badges16 bronze badges
For directories, you want to do:
ln -sfT /location/to/new/target old_linkname
answered Apr 2, 2014 at 21:48
raaraa
911 silver badge2 bronze badges
1
No. The symlink system call will return EEXIST if newpath already exists. You can only link from a new node in the filesystem. What’s the requirement here? If you’re worried about a race due to the non-atomicity of the unlink/symlink calls, then you might want to rethink the architecture a little to provide synchronization elsewhere. There have been some scary security bugs introduced by this kind of thing.
answered Nov 13, 2009 at 5:33
Andy RossAndy Ross
11.6k1 gold badge34 silver badges31 bronze badges
0
As others have mentioned, you basically have to delete the symlink first, either manually or by passing the -f flag to the ln utility.
Years ago, I had to make small edits to symlinks pretty frequently, so I wrote a simple readline-based utility (edln) to make this less annoying. In case anyone else finds it useful, I’ve put it online at https://github.com/jjlin/edln/.
edln will display the original symlink target; you can then use the arrow keys, or standard readline keystrokes (M-b, M-f, C-d, etc.) to move around and edit the target.
answered May 7, 2012 at 0:46
jjlinjjlin
4,4021 gold badge29 silver badges23 bronze badges
5
Chain the commands like this:
rm currentlink && ln -s /path/to/link currentlink
The first command removes the existing one and the 2nd immediately creates it again.
answered Feb 26, 2013 at 9:20
PetePete
1,28910 silver badges18 bronze badges
Just googled, found no good answer and had to solve myself:
ln -f -s -T `readlink SomeLibrary | sed 's/version.old/version.new/'` SomeLibrary
Editing by definition means not recreating from scratch but changing partly. Any answer requiring to memorize a path, maybe long or with weird symbols, is definitely bad.
answered Aug 29, 2014 at 11:32
user1046885user1046885
1712 silver badges7 bronze badges
Как создавать и удалять симлинки


Используемые термины: Симлинк, Windows, Linux.
Работы с символьными ссылками в Windows ведутся из командной строки.
Синтаксис
mklink <имя создаваемого симлинка> <на что ведет симлинк>
Симлинк на файл
mklink C:UsersdmoskDesktopcmd.exe C:Windowssystem32cmd.exe
* в данном примере на рабочем столе пользователя dmosk будет создан симлинк на файл cmd.exe.
Симлинк на директорию
mklink /D «C:UsersdmoskDesktopСетевая папка» \dmosk.localshare
* в примере создается симлинк на сетевую папку \dmosk.localshare
** так как в названии папки есть пробел, путь заключен в кавычки.
Для создания ссылки на папку доступен также ключ /J. Созданная таким образом ссылка будет по некоторым особенностям напоминать жесткую ссылку.
Удалить симлинк
В Windows его можно удалить в проводнике, как обычный файл или папку.
Или использовать командную строку.
Для папки:
rmdir «C:UsersdmoskDesktopСетевая папка»
Для файла:
del C:UsersdmoskDesktopcmd.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 с -f force и даже для каталогов -n (inode можно использовать повторно): ln -sfn / some / new / path имя ссылки.
- Удалите символическую ссылку и создайте новую (даже для каталогов): rm linkname; ln -s / some / new / path имя ссылки.
Можете ли вы отредактировать файл символьной ссылки?
Нет. Системный вызов символической ссылки вернет EEXIST, если новый путь уже существует. Вы можете ссылаться только с нового узла в файловой системе.
Можно ли переименовать символьную ссылку?
Что произойдет с символической ссылкой, если мы переименуем файл? После перемещения файла, на который указывает символическая ссылка, символическая ссылка сломано ака висящая символическая ссылка. Вы должны удалить его и создать новый, если хотите указать на новое имя файла.
Как изменить символическую ссылку?
Поскольку символические ссылки не имеют режимов chmod не влияет на символические ссылки. Если файл обозначает каталог, chmod изменяет режим каждого файла во всем поддереве, подключенном в этот момент. Не переходите по символическим ссылкам. Поскольку у символьных ссылок нет режимов, chmod не влияет на символьные ссылки.
Как удалить символическую ссылку в Linux?
Чтобы удалить символическую ссылку, используйте либо команда rm или unlink, за которой следует имя символической ссылки в качестве аргумента. При удалении символической ссылки, указывающей на каталог, не добавляйте косую черту в конце имени символической ссылки.
Почему нет жестких ссылок на каталоги?
Причина жесткой привязки каталогов не допускается немного технический. По сути, они нарушают структуру файловой системы. В любом случае вам не следует использовать жесткие ссылки. Символические ссылки позволяют использовать большинство тех же функций, не вызывая проблем (например, ln -s target link).
Как создать символическую ссылку?
Чтобы создать символическую ссылку, используйте параметр -s (–символический). Если заданы и FILE, и LINK, ln создаст ссылку из файла, указанного в качестве первого аргумента (FILE), на файл, указанный в качестве второго аргумента (LINK).
Что будет, если вы удалите символическую ссылку?
Если символическая ссылка удалена, его цель остается незатронутой. Если символическая ссылка указывает на цель, и когда-то позже эта цель перемещается, переименовывается или удаляется, символическая ссылка не обновляется или удаляется автоматически, но продолжает существовать и по-прежнему указывает на старую цель, теперь несуществующее местоположение или файл.
Как найти символьную ссылку?
Чтобы просмотреть символические ссылки в каталоге:
- Откройте терминал и перейдите в этот каталог.
- Введите команду: ls -la. Это будет длинный список всех файлов в каталоге, даже если они скрыты.
- Файлы, начинающиеся с l, являются вашими файлами символических ссылок.

Linux и FreeBSD