Bash – How to determine callee function name in a script

bashfunctionshell-script

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?

Best Answer

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
Related Question