Bash:如何获得符号链接的真实路径? [英] Bash: how to get real path of a symlink?

查看:53
本文介绍了Bash:如何获得符号链接的真实路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过执行/usr/local/bin文件夹中的符号链接文件来获取原始脚本的绝对路径?好吧,..我知道原始文件在哪里,并且我知道它,因为我正在链接它.但是,即使我移动了原始源代码(和符号链接),我也希望此脚本能够正常工作.

Is it possible, executing a file symlinked in /usr/local/bin folder, to get the absolute path of original script? Well, .. I know where original file is, and I know it because I am linkging it. But, ... I want this script working, even if I move original source code (and symlink).

#!/bin/bash
echo "my path is ..."

推荐答案

readlink 不是标准命令,但是它在Linux和BSD(包括OS X)上很常见,它是解决问题的最直接的方法你的问题.BSD和GNU readlink的实现是不同的,因此请阅读您所拥有的文档.

readlink is not a standard command, but it's common on Linux and BSD, including OS X, and it's the most straightforward answer to your question. BSD and GNU readlink implementations are different, so read the documentation for the one you have.

如果 readlink 不可用,或者您需要编写不受特定实现约束的跨平台脚​​本,则:

If readlink is not available, or you need to write a cross-platform script that isn't bound to a specific implementation:

如果符号链接也是目录,则

If the symlink is also a directory, then

cd -P "$symlinkdir"

将使您进入已取消引用的目录,所以

will get you into the dereferenced directory, so

echo "I am in $(cd -P "$symlinkdir" && pwd)"

将回显完全取消引用的目录.就是说, cd -P 取消了整个路径的引用,因此,如果同一路径中有多个符号链接,则会产生意外的结果.

will echo the fully dereferenced directory. That said, cd -P dereferences the entire path, so if you have more than one symlink in the same path you can have unexpected results.

如果符号链接指向文件而不是目录,则可能不需要取消引用链接.大多数命令无害地遵循符号链接.如果只想检查文件是否为链接,请使用 test -L .

If the symlink is to a file, not a directory, you may not need to dereference the link. Most commands follow symlinks harmlessly. If you simply want to check if a file is a link, use test -L.

这篇关于Bash:如何获得符号链接的真实路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆