bash 如何从函数内部确定函数名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1835943/
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
How to determine function name from inside a function
提问by Yan
If I have a Bash script like:
如果我有一个 Bash 脚本,例如:
#!/bin/bash
f() {
# echo function name, "f" in this case
}
Is there any way to do this? This could be used in help messages such as
有没有办法做到这一点?这可以用于帮助消息,例如
printf "Usage: %s: blah blah blah \n" $(basename # in a file "foobar"
function foo {
echo foo
echo "In function $FUNCNAME: FUNCNAME=${FUNCNAME[*]}" >&2
}
function foobar {
echo "$(foo)bar"
echo "In function $FUNCNAME: FUNCNAME=${FUNCNAME[*]}" >&2
}
foobar
) >&2;
Only in this case what I wanted is not $0
, which is the file name of the script.
只有在这种情况下,我想要的不是$0
,这是脚本的文件名。
回答by TheBonsai
You can use ${FUNCNAME[0]}
in bash
to get the function name.
您可以使用${FUNCNAME[0]}
inbash
来获取函数名称。
回答by bschlueter
From the Bash Reference Manual:
来自Bash 参考手册:
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 bottom-most element (the one with the highest index) 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.
This variable can be used with BASH_LINENO and BASH_SOURCE. Each element of FUNCNAME has corresponding elements in BASH_LINENO and BASH_SOURCE to describe the call stack. For instance, ${FUNCNAME[$i]} was called from the file ${BASH_SOURCE[$i+1]} at line number ${BASH_LINENO[$i]}. The caller builtin displays the current call stack using this information.
函数名
一个数组变量,包含当前在执行调用堆栈中的所有 shell 函数的名称。索引为 0 的元素是任何当前正在执行的 shell 函数的名称。最底部的元素(索引最高的元素)是“main”。此变量仅在执行 shell 函数时存在。对 FUNCNAME 的赋值无效并返回错误状态。如果 FUNCNAME 未设置,它会失去其特殊属性,即使它随后被重置。
此变量可与 BASH_LINENO 和 BASH_SOURCE 一起使用。FUNCNAME 的每个元素在 BASH_LINENO 和 BASH_SOURCE 中都有对应的元素来描述调用栈。例如,${FUNCNAME[$i]} 是从文件 ${BASH_SOURCE[$i+1]} 行号 ${BASH_LINENO[$i]} 处调用的。内置调用者使用此信息显示当前调用堆栈。
When bash arrays are accessed without an index the first element of the array will be returned, so $FUNCNAME
will work in simple cases to provide the name of the immediately current function, but it also contains all other functions in the call stack. For example:
当在没有索引的情况下访问 bash 数组时,将返回数组的第一个元素,因此$FUNCNAME
在简单情况下可以提供当前函数的名称,但它也包含调用堆栈中的所有其他函数。例如:
$ bash foobar
In function foo: FUNCNAME=foo foobar main
foobar
In function foobar: FUNCNAME=foobar main
Will output:
将输出:
##代码##回答by Verdigrass
I use ${FUNCNAME[0]}
to print current function name
我${FUNCNAME[0]}
用来打印当前函数名