Bash:将函数作为参数传递 [英] Bash: pass a function as parameter
本文介绍了Bash:将函数作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在 Bash 中传递一个函数作为参数.例如下面的代码:
I need to pass a function as a parameter in Bash. For example, the following code:
function x() {
echo "Hello world"
}
function around() {
echo "before"
eval $1
echo "after"
}
around x
应该输出:
before
Hello world
after
我知道 eval
在那种情况下是不正确的,但这只是一个例子:)
I know eval
is not correct in that context but that's just an example :)
有什么想法吗?
推荐答案
如果你不需要任何花哨的东西,比如延迟函数名或其参数的计算,你就不需要 eval
:
If you don't need anything fancy like delaying the evaluation of the function name or its arguments, you don't need eval
:
function x() { echo "Hello world"; }
function around() { echo before; $1; echo after; }
around x
做你想做的.您甚至可以通过这种方式传递函数及其参数:
does what you want. You can even pass the function and its arguments this way:
function x() { echo "x(): Passed $1 and $2"; }
function around() { echo before; "$@"; echo after; }
around x 1st 2nd
印刷品
before
x(): Passed 1st and 2nd
after
这篇关于Bash:将函数作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文