bash 可以显示函数的定义吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6916856/
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
Can bash show a function's definition?
提问by k107
Is there a way to view a bash function's definition in bash?
有没有办法在 bash 中查看 bash 函数的定义?
For example, say I defined the function foobar
例如,假设我定义了函数 foobar
function foobar {
echo "I'm foobar"
}
Is there any way to later get the code that foobar
runs?
以后有什么办法可以得到foobar
运行的代码吗?
$ # non-working pseudocode
$ echo $foobar
echo "I'm foobar"
回答by Benjamin Bannier
Use type
. If foobar
is e.g. defined in your ~/.profile
:
使用type
. 如果foobar
例如在您的定义中~/.profile
:
$ type foobar
foobar is a function
foobar {
echo "I'm foobar"
}
This does find out what foobar
was, and if it was defined as a function it calls declare -f
as explained by pmohandras.
这确实找出了是什么foobar
,如果它被定义为一个函数,它会declare -f
按照 pmohandras 的解释调用。
To print out just the body of the function (i.e. the code) use sed
:
要仅打印出函数的主体(即代码),请使用sed
:
type foobar | sed '1,3d;$d'
回答by pmohandas
You can display the definition of a function in bash using declare. For example:
您可以使用declare 在bash 中显示函数的定义。例如:
declare -f foobar
回答by Jurgen van der Mark
set | sed -n '/^foobar ()/,/^}/p'
This basically prints the lines from your set command starting with the function name foobar () and ending with }
这基本上打印了 set 命令中以函数名称 foobar () 开头并以 } 结尾的行
回答by pyroscope
set | grep -A999 '^foobar ()' | grep -m1 -B999 '^}'
with foobar being the function name.
foobar 是函数名。