Bash: pass a function as parameter

cd1 picture cd1 · Apr 15, 2011 · Viewed 40.4k times · Source

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?

Answer

Idelic picture Idelic · Apr 15, 2011

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

prints

before
x(): Passed 1st and 2nd
after