78

所以我创建了一个符号链接:

ln -s /location/to/link linkname

现在我想更改符号链接链接到的位置。我怎么做?有没有办法在不先删除它的情况下做到这一点?

4

10 回答 10

53

您可以使用不同的名称创建新链接,然后移动它以替换旧链接。

ln -s /location/to/link linkname

之后

ln -s /location/to/link2 newlink
mv newlink linkname

如果newlinklinkname位于同一物理设备上,则mv应该是原子的。

于 2009-11-13T07:01:03.207 回答
30

试试ln -sf new_destination linkname

于 2009-11-13T05:33:46.373 回答
23

只需更改符号链接目标:

# ln -sfT /path/to/new/target linkname

这是一个瞬间的原子变化。

于 2015-02-18T05:08:34.760 回答
17

如果符号链接目标是目录,则需要-T在命令中添加标志mv,否则它将新符号链接移动到旧符号链接的目标目录中。

以原子方式将网站切换到新版本的示例:

原始设置 - 网站存储在www1目录中,vhost 指向www符号链接:

ln -s www1 www

浏览网站,查看旧版本。

将新网站文件放在新www2目录中。

设置指向新网站的新符号链接:

ln -s www_new www2

www符号链接移动到新网站的目录:

mv -T www_new www

浏览网站,立即查看新版本。

于 2013-03-26T17:44:00.267 回答
8

在 OSX 上,ln 的手册页说你可以这样做

ln -shf /location/to/link link name

从手册页:

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.
于 2014-02-17T21:30:05.837 回答
7

对于目录,您要执行以下操作: ln -sfT /location/to/new/target old_linkname

于 2014-04-02T21:48:04.760 回答
5

否。如果 newpath 已经存在,symlink系统调用将返回。EEXIST您只能从文件系统中的新节点链接。这里有什么要求?如果您担心由于 unlink/symlink 调用的非原子性而导致的竞争,那么您可能需要重新考虑一下架构以在其他地方提供同步。这种事情已经引入了一些可怕的安全漏洞。

于 2009-11-13T05:33:19.803 回答
4

像这样链接命令:

rm currentlink && ln -s /path/to/link currentlink

第一个命令删除现有的,第二个命令立即再次创建它。

于 2013-02-26T09:20:10.303 回答
3

正如其他人所提到的,您基本上必须先手动删除符号链接,或者将-f标志传递给ln实用程序。

几年前,我不得不经常对符号链接进行小幅编辑,因此我编写了一个简单的基于 readline 的实用程序 ( edln) 来减少这方面的烦人。万一其他人觉得它有用,我已经把它放在了https://github.com/jjlin/edln/上。

edln将显示原始符号链接目标;然后,您可以使用箭头键或标准的 readline 击键(M-bM-fC-d等)来移动和编辑目标。

于 2012-05-07T00:46:10.443 回答
1

刚用谷歌搜索,没有找到好的答案,不得不自己解决:

ln -f -s -T `readlink SomeLibrary | sed 's/version.old/version.new/'` SomeLibrary

按定义编辑意味着不是从头开始重新创建,而是部分改变。任何需要记住路径的答案,可能很长或带有奇怪的符号,绝对是不好的。

于 2014-08-29T11:32:38.080 回答