获取调用函数的脚本的文件名

获取调用函数的脚本的文件名

本文介绍了zsh:获取调用函数的脚本的文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在函数内部,如何获取调用该函数的任何脚本的文件名?

Inside a function, how can I get the file name of whatever script called that function?

通过提示扩展,%x 提供定义函数的文件名.%N 提供函数名.如何获得调用函数的文件名?

Via prompt expansion, %x provides the name of the file that defines the function. %N provides the function name. How do I get the name of the file that called the function?

这对于报告我的每个启动脚本的运行时间很有用,例如:

This would be useful to report the runtime of each of my startup scripts, e.g.:

~/.zshenv:

function start_timer() {
  start_time=$(date +%s.%N)
}
function stop_timer() {
  stop_time=$(date +%s.%N)
  elapsed_time=$((stop_time-start_time))
  echo "$SCRIPTNAME took $elapsed_time seconds"
}
start_timer
# initialize env...
end_timer # "~/.zshenv took 0 seconds"

~/.zshrc:

start_timer
# initialize interactive shell...
end_timer # "~/.zshrc took 2 seconds"

~/.zlogin:

start_timer
# initialize login shell...
end_timer # "~/.zlogin took 2 seconds"

推荐答案

至少在 zsh 5.7.1 中,ZSH_ARGZERO 变量会报告当前脚本的名称,即使其中的函数它叫不同:

At least in zsh 5.7.1, the ZSH_ARGZERO variable will report the name of the current script, even if the function within which it is called is different:

$ cat foo
function a_function_in_foo {
    echo "ZSH_ARGZERO=$ZSH_ARGZERO"
}
$ cat bar
source foo
a_function_in_foo
$ zsh bar
ZSH_ARGZERO=bar

记录在 http://zsh.sourceforge.net/Doc/Release/Parameters.html

ZSH_ARGZERO

如果调用 zsh 来运行脚本,则这是脚本的名称.否则,它是用于调用当前 shell 的名称.这与设置 POSIX_ARGZERO 选项时 $0 的值相同,但始终可用.

If zsh was invoked to run a script, this is the name of the script. Otherwise, it is the name used to invoke the current shell. This is the same as the value of $0 when the POSIX_ARGZERO option is set, but is always available.

这篇关于zsh:获取调用函数的脚本的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 03:13