加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Bash:传递一个函数作为参数

发布时间:2020-12-15 16:22:51 所属栏目:安全 来源:网络整理
导读:我需要传递一个函数作为参数在Bash。例如,下面的代码: function x() { echo "Hello world"}function around() { echo "before" eval $1 echo "after"}around x 应输出: beforeHello worldafter 我知道eval在这种情况下是不正确的,但这只是一个例子:) 任
我需要传递一个函数作为参数在Bash。例如,下面的代码:
function x() {
  echo "Hello world"
}

function around() {
  echo "before"
  eval $1
  echo "after"
}

around x

应输出:

before
Hello world
after

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

任何想法?

如果你不需要任何像延迟函数名或其参数的计算的东西,你不需要eval:
function x()      { echo "Hello world";          }
function around() { echo before; $1; echo after; }

around x

做你想要的。你甚至可以这样传递函数及其参数:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读