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

Yun*_*ang 46 bash shell

在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
Run Code Online (Sandbox Code Playgroud)

Fat*_*ror 82

试试${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.
Run Code Online (Sandbox Code Playgroud)

  • 当然.在这方面,您可能还会发现`BASH_LINENO`的内容很有用. (5认同)

Wil*_*ell 32

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

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

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