如何使用 bash 确定链接指向哪个目录
使用 Bash 脚本,有没有办法确定链接指向哪个目录,然后根据结果将其切换到另一个目录?
例如,假设我有以下两个目录:
/var/data/1/
和 /var/data/2/
我有其中一个目录的链接,例如, data_link
并且当前链接到 /var/data/1/
当触发脚本时,我希望它将链接交换到 /var/data /2/
(即ln -s /var/data/2/ /somepath/data_link
)。
当再次触发脚本时,会发生相反的情况(即ln -s /var/data/1/ /somepath/data_link ),依此类推。通过 Bash 脚本执行此操作的最简单方法是什么?
With Bash scripting, is there a way to determine which directory a link is pointing to, then switch it to another directory based on the result?
For example, say I have the two following directories:
/var/data/1/
and /var/data/2/
I have a link to one of them, say, data_link
and it is currently linked to /var/data/1/
When the script is triggered, I want it to swap the link to /var/data/2/
(i.e. ln -s /var/data/2/ /somepath/data_link
).
When the script is triggered again, the opposite will happen (i.e. ln -s /var/data/1/ /somepath/data_link
), and so on. What's the easiest way to do this via a Bash script?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不幸的是,标准的 Unix 实用程序集不包括对 readlink 系统调用的轻松访问。某些系统包含
readlink
命令。如果可用,readlink foo
很有可能打印符号链接foo
的目标。如果您想使用选项,请注意该命令有多个版本;即使在 Linux 发行版之间也无法获得可移植性。如果您有可用的 perl,
perl -e 'print readlink $ARGV[0]' mylink
会打印mylink
的目标。如果您需要一种可移植的方式并且没有 Perl 或其他任何理智的东西,您也许可以通过解析 ls -l mylink 的输出来凑合。
如果您有指向有权更改的目录的符号链接,则
$(cd mylink && command -p pwd)
是链接最终目标的绝对路径。例如,如果foo
是/var/tmp/bar
的符号链接,则bar
是/var/tmp< 中的目录/code> 和
/var/tmp
是到/tmp
的符号链接,此命令生成/tmp/bar
。Unfortunately, the standard set of unix utilities doesn't include an easy access to the
readlink
system call. Some systems include areadlink
command. If it's available, there's a good chance thatreadlink foo
prints the target of the symlinkfoo
. If you feel tempted to use options, be warned that there are multiple versions of this command floating around; you won't get portability even between Linux distributions.If you have perl available,
perl -e 'print readlink $ARGV[0]' mylink
prints the target ofmylink
.If you need a portable way and don't have Perl or anything else sane, you can perhaps make do with parsing the output of
ls -l mylink
.If you have a symbolic link to a directory that you have permission to change into, then
$(cd mylink && command -p pwd)
is the absolute path to the ultimate target of the link. For example, iffoo
is a symlink to/var/tmp/bar
,bar
is a directory in/var/tmp
and/var/tmp
is a symbolic link to/tmp
, this command yields/tmp/bar
.使用
readlink
命令获取链接的内容:然后使用标准
if
检查当前值,使用rm
删除它,然后 < code>ln 正如您指示的那样使用新的所需目标重新创建。Use the
readlink
command to get the content of a link:Then use standard
if
to inspect the current value,rm
to remove it, andln
as you indicated to re-create with the new desired target.