所以我创建了一个符号链接:
ln -s /location/to/link linkname
现在我想更改符号链接链接到的位置。我怎么做?有没有办法在不先删除它的情况下做到这一点?
您可以使用不同的名称创建新链接,然后移动它以替换旧链接。
ln -s /location/to/link linkname
之后
ln -s /location/to/link2 newlink
mv newlink linkname
如果newlink
和linkname
位于同一物理设备上,则mv
应该是原子的。
试试ln -sf new_destination linkname
。
只需更改符号链接目标:
# ln -sfT /path/to/new/target linkname
这是一个瞬间的原子变化。
如果符号链接目标是目录,则需要-T
在命令中添加标志mv
,否则它将新符号链接移动到旧符号链接的目标目录中。
以原子方式将网站切换到新版本的示例:
原始设置 - 网站存储在www1
目录中,vhost 指向www
符号链接:
ln -s www1 www
浏览网站,查看旧版本。
将新网站文件放在新www2
目录中。
设置指向新网站的新符号链接:
ln -s www_new www2
将www
符号链接移动到新网站的目录:
mv -T www_new www
浏览网站,立即查看新版本。
在 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.
对于目录,您要执行以下操作: ln -sfT /location/to/new/target old_linkname
否。如果 newpath 已经存在,symlink
系统调用将返回。EEXIST
您只能从文件系统中的新节点链接。这里有什么要求?如果您担心由于 unlink/symlink 调用的非原子性而导致的竞争,那么您可能需要重新考虑一下架构以在其他地方提供同步。这种事情已经引入了一些可怕的安全漏洞。
像这样链接命令:
rm currentlink && ln -s /path/to/link currentlink
第一个命令删除现有的,第二个命令立即再次创建它。
正如其他人所提到的,您基本上必须先手动删除符号链接,或者将-f
标志传递给ln
实用程序。
几年前,我不得不经常对符号链接进行小幅编辑,因此我编写了一个简单的基于 readline 的实用程序 ( edln
) 来减少这方面的烦人。万一其他人觉得它有用,我已经把它放在了https://github.com/jjlin/edln/上。
edln
将显示原始符号链接目标;然后,您可以使用箭头键或标准的 readline 击键(M-b
、M-f
、C-d
等)来移动和编辑目标。
刚用谷歌搜索,没有找到好的答案,不得不自己解决:
ln -f -s -T `readlink SomeLibrary | sed 's/version.old/version.new/'` SomeLibrary
按定义编辑意味着不是从头开始重新创建,而是部分改变。任何需要记住路径的答案,可能很长或带有奇怪的符号,绝对是不好的。