4

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?

9

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
  • Consider updating the zsh answer with ${funcstack[@]:0:1} which works whether array indexing starts at 0 (option KSH_ARRAYS) or 1 (default) – Tom Hale May 25 at 13:50
4

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

0
function tt { echo ${FUNCNAME}; }

does it on my CentOS 6 box.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.