在BASH中,是否可以在函数体中获取函数名?

在BASH中,是否可以在函数体中获取函数名? 以下面的代码为例,我想在它的主体中打印函数名“Test”,但是“$ 0”似乎是指脚本名而不是函数名。 那么如何获得函数名?

#!/bin/bash function Test { if [ $# -lt 1 ] then # how to get the function name here? echo "$0 num" 1>&2 exit 1 fi local num="${1}" echo "${num}" } # the correct function Test 100 # missing argument, the function should exit with error Test exit 0 

尝试${FUNCNAME[0]} 。 这个数组包含当前的调用堆栈。 引用手册页:

  FUNCNAME An array variable containing the names of all shell functions currently in the execution call stack. The element with index 0 is the name of any currently-executing shell function. The bot‐ tom-most element is "main". This variable exists only when a shell function is executing. Assignments to FUNCNAME have no effect and return an error status. If FUNCNAME is unset, it loses its special properties, even if it is subsequently reset. 

该函数的名称在${FUNCNAME[ 0 ]} 。FUNCNAME是一个包含调用堆栈中所有函数名称的数组,因此:

 $ ./sample
 FOO
酒吧
 $猫样本
 #!/斌/庆典

 foo(){
         echo $ {FUNCNAME [0]}#打印'foo'
         echo $ {FUNCNAME [1]}#打印“bar”
 }
 bar(){foo;  }
酒吧