How to determine function name from inside a function

Viewed 72055

If I have a Bash script like:

#!/bin/bash

f() {
  # echo function name, "f" in this case
}

Is there any way to do this? This could be used in help messages such as

printf "Usage: %s: blah blah blah \n" $(basename $0) >&2; 

Only in this case what I wanted is not $0, which is the file name of the script.

5 Answers

The simplest way to get the function name (from inside a function) is dependent on which shell you are using:

Zsh version
someFunctionName() {
   echo $funcstack[1]
}
Bash version
someFunctionName() {
   echo ${FUNCNAME[0]}
}
Both
someFunctionName() {
  currentShell=$(ps -p $$ | awk "NR==2" | awk '{ print $4 }' | tr -d '-')
  if [[ $currentShell == 'bash' ]]; then
    echo ${FUNCNAME[0]}
  elif [[ $currentShell == 'zsh' ]]; then
    echo $funcstack[1]
  fi
}
A more robust version
columnX () {
    awk "{print \$$1}"
}
rowX () {
    awk "NR==$1"
}

checkShell() {
    ps -p $$ | columnX 4 | rowX 2 | tr -d - 
    # produces bash or zsh (or other shell name like fish)
}

showMethodName(){
    checkShell && echo ${FUNCNAME[0]} || echo $funcstack[1] 
}
showMethodName

Another example:

# in a file "foobar"
foo() {
    echo "$FUNCNAME fuction begins"
}

foobar() {
    echo "$FUNCNAME fuction begins"
}

echo 'begin main'
foo
foobar
echo 'end main'

Will output:

begin main
foo fuction begins
foobar fuction begins
end main
Related