“安全地”替换重要的符号链接
我想从 bash 脚本中更改符号链接的目标。问题是符号链接非常重要(即 /bin/sh
),我会这样做:
- 删除旧目标后,新目标将立即可用,即不会有某些东西会注意到它消失的可能性,
- 更改不可能在中间失败,即让用户删除符号链接并且没有新的符号链接。
我想了两种方法。使用普通的 ln
:
ln -fs /bin/bash /bin/sh
或使用 mv
:
ln -s /bin/bash /bin/sh.new
mv /bin/sh.new /bin/sh
哪一个更适合我的需求?其中之一是否有可能尝试替换符号链接目标而不是符号链接本身?
I would like to change the target of symbolic link from within a bash script. The problem is that the symlink is quite important (it's /bin/sh
, namely) and I would to do it in fashion that:
- New target will be available immediately after removing old, i.e. there will be no possibility that something will notice disappearing of it,
- There will be no possibility that the change will fail in the middle, i.e. leaving user with symlink removed and no new one.
I thought about two methods. Either using plain ln
:
ln -fs /bin/bash /bin/sh
or using mv
:
ln -s /bin/bash /bin/sh.new
mv /bin/sh.new /bin/sh
Which one will suit my needs better? Is there any possibility that one of them would try to replace the symlink target instead of symlink itself?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
重命名(
mv
)是一个原子操作;创建新的符号链接不是(删除旧的符号链接;创建新的符号链接)。所以你应该使用mv
:这是一个博客文章讨论了这个问题。另外,如果您担心会发生什么,为什么不先在非关键符号链接上尝试呢?
Renaming (
mv
) is an atomic operation; creating a new symlink is not (delete old symlink; create new one). So you should usemv
:Here's a blog post discussing this. Also, if you're worried about what will happen, why not try it on a non-critical symlink first?
看起来(从手册页来看)
ln -f
在创建新符号链接之前取消了符号链接,这意味着mv
是更好的选择。不过,我强烈建议反对将
/bin/sh
链接到bash
。许多脚本使用:并且在编写时假设 shell 是经典的 Bourne shell。如果要运行
bash
,您很容易会发现脚本假定的sh
执行的操作与bash
实际执行的操作之间存在模糊的不兼容性。 /em> 确实如此。这些几乎不可能被追踪到。It looks like (from the man page)
ln -f
unlinks the symlink before making the new one, which meansmv
is the better option for this.I would, however, strongly recommend against linking
/bin/sh
tobash
. Many scripts use:and are written assuming that the shell is the classic Bourne shell. If this were to run
bash
instead, you could easily get obscure incompatibilities between what the script assumessh
does and whatbash
actually does. These will be nearly impossible to track down.