How to determine callee function name in a script

7,782

Solution 1

In bash, use FUNCNAME array:

tt() {
  printf '%s\n' "$FUNCNAME"
}

With some ksh implementations:

tt() { printf '%s\n' "$0"; }

In ksh93:

tt() { printf '%s\n' "${.sh.fun}"; }

From ksh93d and above, you can also use $0 inside function to get the function name, but you must define function using function name { ...; } form.


In zsh, you can use funcstack array:

tt() { print -rl -- $funcstack[1]; }

or $0 inside function.


In fish:

function tt
  printf '%s\n' "$_"
end

Solution 2

In bash, you can use ${FUNCNAME[0]}.

Share:
7,782
NicolasW
Author by

NicolasW

Updated on September 18, 2022

Comments

  • NicolasW
    NicolasW almost 2 years

    To make it short, doing something like:

    -bash$ function tt
    {
     echo $0;
    }
    
    -bash$ tt
    

    $0 will return -bash, but how to get the function name called, i.e. tt in this example instead?

  • Tom Hale
    Tom Hale about 5 years
    Consider updating the zsh answer with ${funcstack[@]:0:1} which works whether array indexing starts at 0 (option KSH_ARRAYS) or 1 (default)