[英]How to read the current folder from a script when it's called with source (same shell) or bash (subshell)?
This is a hard one, as I have researched for a few hours and could not find a solution that works, so I combined a few of solutions that I found and this is the results:这是一个很难的问题,因为我研究了几个小时但找不到可行的解决方案,所以我结合了一些我找到的解决方案,结果如下:
"$( cd "$( dirname "${BASH_SOURCE[0]}" )" && dirname -- "$(readlink -f -- "$0")" )"
If anyone has a simpler one, please share otherwise, enjoy!如果有人有更简单的,请分享,否则,享受!
I don't think that there is a solution for bash which works in every circumstance (for instance when sourcing a file via a link), but this approach might work most of the time:我不认为 bash 的解决方案适用于任何情况(例如通过链接获取文件时),但这种方法可能在大多数情况下都有效:
${BASH_SOURCE[0]}
contains the name of the script including PATH component, in the way it is invoked. ${BASH_SOURCE[0]}
包含脚本的名称,包括 PATH 组件,以它被调用的方式。 If it was invoked via a $PATH
search, it contains that respective PATH.如果它是通过$PATH
搜索调用的,则它包含相应的 PATH。 Hence, dirname "${BASH_SOURCE[0]}"
would be the directory, where the script is located (either as relative or absolute path).因此, dirname "${BASH_SOURCE[0]}"
将是脚本所在的目录(相对路径或绝对路径)。 Consequently, readlink -f -- $(dirname "${BASH_SOURCE[0]}")
would output the absolute path to this directory.因此, readlink -f -- $(dirname "${BASH_SOURCE[0]}")
将 output 该目录的绝对路径。 Hence to locate other_script
in the same directory would be:因此,在同一目录中找到other_script
将是:
source "$(readlink -f -- $(dirname "${BASH_SOURCE[0]}"))/other_script" # bash
You tagged your question also for zsh .您也为zsh标记了您的问题。 In Zsh, things are a bit simpler.在 Zsh 中,事情要简单一些。 You find your script (plus directory part) in $0
.您在$0
中找到您的脚本(加上目录部分)。 The absolute path of the directory is hence returned $0:A
, giving you因此返回目录的绝对路径$0:A
,给你
source $0:A/other_script # zsh
Of course, if you need this information only for sourcing the other script, you don't need to get the absolute path to other_script
.当然,如果您只需要此信息来获取其他脚本,则不需要获取other_script
的绝对路径。 The relative path would do as well.相对路径也可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.