Можно ли получить имя функции в теле функции?
В BASH можно ли получить имя функции в теле функции? Принимая следующие коды в качестве примера, я хочу напечатать имя функции "Test" в своем теле, но "$ 0", похоже, ссылается на имя script вместо имени функции. Итак, как получить имя функции?
#!/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
Ответы
Ответ 1
Попробуйте ${FUNCNAME[0]}
. Этот массив содержит текущий стек вызовов. Чтобы процитировать страницу man:
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.
Ответ 2
Имя функции находится в ${FUNCNAME[ 0 ]}
FUNCNAME - это массив, содержащий все имена функций в стеке вызовов, поэтому:
$ ./sample
foo
bar
$ cat sample
#!/bin/bash
foo() {
echo ${FUNCNAME[ 0 ]} # prints 'foo'
echo ${FUNCNAME[ 1 ]} # prints 'bar'
}
bar() { foo; }
bar