bash 是否可以在函数体中获取函数名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9146623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:37:51  来源:igfitidea点击:

Is it possible to get the function name in function body?

bashshell

提问by Yun Huang

In BASH, is it possible to get the function name in function body? Taking following codes as example, I want to print the function name "Test" in its body, but "$0" seems to refer to the script name instead of the function name. So how to get the function name?

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

#!/bin/bash

function Test
{
    if [ $# -lt 1 ]
    then
        #   how to get the function name here?
        echo "
   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.
num" 1>&2 exit 1 fi local num="" echo "${num}" } # the correct function Test 100 # missing argument, the function should exit with error Test exit 0

回答by FatalError

Try ${FUNCNAME[0]}. This array contains the current call stack. To quote the man page:

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

$ ./sample
foo
bar
$ cat sample
#!/bin/bash

foo() {
        echo ${FUNCNAME[ 0 ]}  # prints 'foo'
        echo ${FUNCNAME[ 1 ]}  # prints 'bar'
}
bar() { foo; }
bar

回答by William Pursell

The name of the function is in ${FUNCNAME[ 0 ]}FUNCNAME is an array containing all the names of the functions in the call stack, so:

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

##代码##