Get name of calling function in zsh

我只是一个虾纸丫 提交于 2020-03-18 11:56:46

问题


I want to get function caller name in shell script sometime, in bash it works with ${FUNCNAME[1]}

${FUNCNAME[1]} is a (caller name)

${FUNCNAME[0]} is c (current name)

but it not work in zsh

ie i want to know which function call me in function c

function a(){
    c
}

function b(){
    c
}

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

回答1:


The function call stack is in the variable $funcstack[].

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



回答2:


Generic solution

  • Works whether array indexing starts at 0 (option KSH_ARRAYS) or 1 (default)
  • Works in both zsh and bash

# 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
}

Edge case

The difference between bash and zsh is that when calling this function from a sourced file, bash will say source while zsh will say the name of the file being sourced.



来源:https://stackoverflow.com/questions/31426565/get-name-of-calling-function-in-zsh

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!