Get name of calling function in zsh

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.


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

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

So in c the calling function (a or b) is $funcstack[2] or perhaps more conveniently $funcstack[-1].

Tags:

Zsh