17

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...
}
oguz ismail
  • 1
  • 16
  • 47
  • 69
Chris Brown
  • 357
  • 3
  • 6
  • Duplicate, consider my answer here: https://stackoverflow.com/questions/1835943/how-to-determine-function-name-from-inside-a-function/62527825#62527825 – jasonleonhard Jan 17 '21 at 03:09

2 Answers2

30

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].

alper
  • 2,919
  • 9
  • 53
  • 102
meuh
  • 11,500
  • 2
  • 29
  • 45
  • 3
    zsh array indexes start from 1. There's a compatibility option `KSH_ARRAYS` to start from 0. – meuh Jul 16 '15 at 06:05
  • My edit `${funcstack[1]}` turns out only to be needed with `emulate sh`. Sorry, I can't work out how to revert it. – Tom Hale Jul 03 '18 at 05:28
  • @TomHale It seems you have to edit again, and click *rollback* on the version you want back. I just did it, hope it doesnt cause you any penalty points. Thanks. – meuh Jul 03 '18 at 05:35
  • I had to re-read the second part of your answer three times to understand it, as you mix function names from the question and from your answer. The answer would benefit from rewording it. – kotchwane Jan 08 '22 at 16:13
7

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.

alper
  • 2,919
  • 9
  • 53
  • 102
Tom Hale
  • 40,825
  • 36
  • 187
  • 242