有没有办法在zsh中获取函数调用者名称

Chr*_*own 7 bash shell 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...
}
Run Code Online (Sandbox Code Playgroud)

meu*_*euh 12

函数调用堆栈位于变量中$funcstack[].

$ f(){echo $funcstack[1];}
$ f
f
Run Code Online (Sandbox Code Playgroud)

  • zsh数组索引从1开始.有一个兼容性选项`KSH_ARRAYS`从0开始. (3认同)

Tom*_*ale 6

通用解决方案

  • 无论数组索引从 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
}
Run Code Online (Sandbox Code Playgroud)

边缘情况

bash和之间的区别在于zsh,当从sourced 文件调用此函数时,bash会说sourcewhilezsh会说所来源的文件的名称。