How to determine function name from inside a function

前端 未结 5 877
梦如初夏
梦如初夏 2020-12-02 04:24

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 us

5条回答
  •  春和景丽
    2020-12-02 05:15

    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
    }
    

提交回复
热议问题