如何找到以破折号为源的脚本的路径?

How can I find the path to a script being sourced in dash?

我正在尝试让源 shell 脚本确定它自己的位置,我发现这对 dash 来说是一项艰巨的任务。

在 bash、sh 和 csh 中,我可以使用:$_

在鱼里,我可以用(status -f)

在破折号中,我运气不好...

我已尝试获取如下所示的 path.sh 文件,结果如下:

# path.sh
called=$_
echo called:      $called
echo underscore:  $_
echo zero:        [=10=]
echo dash_source: $DASH_SOURCE
echo bash_source: $BASH_SOURCE

dash -c ". path.sh"

输出:

called:      /usr/local/bin/dash
underscore:  /usr/local/bin/dash
zero:        dash
dash_source:
bash_source:

如何在破折号中获取到 path.sh 的路径?

似乎没有任何便携(POSIX-标准)方法可以做到这一点。

POSIX 指的是采购,因为“dot scripts." While several other parts of the shell language reference do discuss "dot scripts," none of these instances appear to provide any way to find out the path to the currently-executing dot script. In particular, [=10=] 是为 "shell scripts" 保留的,这与 "dot scripts." 不同 "source" 这个词没有出现在任何大写形式的页面或作为任何更大单词的一部分(因此没有 $BASH_SOURCE 之类的东西)。影响 shell 的标准环境变量的 None 似乎也相关。我是会说这在 POSIX 规范中是不可能的。由于 Dash 非常接近 POSIX,因此不太可能针对这种特定情况使用 Dashism(如果它打算这样做,它会'我借用了 $BASH_SOURCE 或创建了一个类似的变量)。

这在 POSIX shell 标准下是不可能的(dash 实现了,仅此而已)。 . 是内置的,而不是 shell 脚本,因此,[=12=] 位置参数指的是 . 的调用者,而 </code> 指的是一个给那个调用者的参数,如果存在的话。特别是,这些东西中的 none 指的是 <code>. 本身或其参数脚本。

如果您可以更改源代码,请将此函数放在所有源代码调用之前。

.() {
   command . ""
}
. script.sh
# more dot scripts

什么是hook 'dot script'函数,现在在函数内部,位置参数就是函数参数。 所以在你的源脚本中,位置参数是:

.         # [=11=]
script.sh # 

正在获取的脚本内部:

# script.sh
echo "$(basename "")"     # this is the name of the script itself

我同意接受的答案,尽管我能够使用 lsof 使其工作:

x=$(lsof -p $$ -Fn0 | tail -1); script=${x#n}

之所以可行,是因为 dash 在脚本执行时保持脚本打开状态。这需要是脚本的第一行,否则如果 dash 稍后打开其他文件描述符,它可能会失败。