Bash: pass a function as parameter

2019-01-30 04:45发布

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

Should output:

before
Hello world
after

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

Any idea?

7条回答
迷人小祖宗
2楼-- · 2019-01-30 05:27

eval is likely the only way to accomplish it. The only real downside is the security aspect of it, as you need to make sure that nothing malicious gets passed in and only functions you want to get called will be called (along with checking that it doesn't have nasty characters like ';' in it as well).

So if you're the one calling the code, then eval is likely the only way to do it. Note that there are other forms of eval that would likely work too involving subcommands ($() and ``), but they're not safer and are more expensive.

查看更多
登录 后发表回答