击:传递函数参数 [英] Bash: pass a function as parameter

查看:172
本文介绍了击:传递函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过一个函数作为击参数。例如,下面的code:

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

我知道评估在这种情况下不正确的,但,这只是一个例子:)

I know eval is not correct in that context but that's just an example :)

任何想法?

推荐答案

如果你不需要任何幻想像延迟功能名称或参数的评价,你不需要评估

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

这篇关于击:传递函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆