获取 zsh 中调用函数的名称

Get name of calling function in zsh

我想在某个时候在 shell 脚本中获取函数调用者名称,在 bash 中它与 ${FUNCNAME[1]}

一起使用

${FUNCNAME[1]} 是一个(来电者姓名)

${FUNCNAME[0]}是c(现名)

但它在 zsh 中不起作用

即我想知道在函数c中哪个函数调用了我

function a(){
    c
}

function b(){
    c
}

function c(){
     #if a call me; then...
     #if b call me; then...
}

函数调用栈在变量$funcstack[]中。

$ f(){echo $funcstack[1];}
$ f
f

所以在 c 中调用函数(ab)是 $funcstack[2] 或者更方便的是 $funcstack[-1].

通用解决方案

  • 无论数组索引从 0(选项 KSH_ARRAYS)还是 1(默认)开始都有效
  • 适用于 zshbash

# Print the name of the function calling me
function func_name () {
  if [[ -n $BASH_VERSION ]]; then
    printf "%s\n" "${FUNCNAME[1]}"
  else  # zsh
    # Use offset:length as array indexing may start at 1 or 0
    printf "%s\n" "${funcstack[@]:1:1}"
  fi
}

边缘情况

bashzsh的区别在于,当从sourced文件调用这个函数时,bash会说source,而zsh 会说出源文件的名称。