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

时间:2012-02-05 03:13:00

标签: 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

2 个答案:

答案 0 :(得分:81)

试试${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.

答案 1 :(得分: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