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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
In bash, use FUNCNAME array:
tt() {
printf '%sn' "$FUNCNAME"
}
With some ksh implementations:
tt() { printf '%sn' "$0"; }
In ksh93:
tt() { printf '%sn' "${.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 '%sn' "$_" end
Method 2
In bash, you can use ${FUNCNAME[0]}.
Method 3
function tt { echo ${FUNCNAME}; }
does it on my CentOS 6 box.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0