“安全地”替换重要的符号链接

发布于 2024-08-03 12:49:22 字数 416 浏览 5 评论 0原文

我想从 bash 脚本中更改符号链接的目标。问题是符号链接非常重要(即 /bin/sh),我会这样做:

  1. 删除旧目标后,新目标将立即可用,即不会有某些东西会注意到它消失的可能性,
  2. 更改不可能在中间失败,即让用户删除符号链接并且没有新的符号链接。

我想了两种方法。使用普通的 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:

  1. New target will be available immediately after removing old, i.e. there will be no possibility that something will notice disappearing of it,
  2. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你爱我像她 2024-08-10 12:49:22

重命名(mv)是一个原子操作;创建新的符号链接不是(删除旧的符号链接;创建新的符号链接)。所以你应该使用mv

$ ln -s new current_tmp && mv -Tf current_tmp current

这是一个博客文章讨论了这个问题。另外,如果您担心会发生什么,为什么不先在非关键符号链接上尝试呢?

Renaming (mv) is an atomic operation; creating a new symlink is not (delete old symlink; create new one). So you should use mv:

$ ln -s new current_tmp && mv -Tf current_tmp current

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?

人海汹涌 2024-08-10 12:49:22

看起来(从手册页来看) ln -f 在创建新符号链接之前取消了符号链接,这意味着 mv 是更好的选择。

不过,我强烈建议反对/bin/sh链接到bash。许多脚本使用:

#!/bin/sh

并且在编写时假设 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 means mv is the better option for this.

I would, however, strongly recommend against linking /bin/sh to bash. Many scripts use:

#!/bin/sh

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 assumes sh does and what bash actually does. These will be nearly impossible to track down.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文