Bash: pass a function as parameter Bash: pass a function as parameter bash bash

Bash: pass a function as parameter


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

beforex(): Passed 1st and 2ndafter


I don't think anyone quite answered the question. He didn't ask if he could echo strings in order. Rather the author of the question wants to know if he can simulate function pointer behavior.

There are a couple of answers that are much like what I'd do, and I want to expand it with another example.

From the author:

function x() {  echo "Hello world"}function around() {  echo "before"  ($1)                   <------ Only change  echo "after"}around x

To expand this, we will have function x echo "Hello world:$1" to show when the function execution really occurs. We will pass a string that is the name of the function "x":

function x() {  echo "Hello world:$1"}function around() {  echo "before"  ($1 HERE)                   <------ Only change  echo "after"}around x

To describe this, the string "x" is passed to the function around() which echos "before", calls the function x (via the variable $1, the first parameter passed to around) passing the argument "HERE", finally echos after.

As another aside, this is the methodology to use variables as function names. The variables actually hold the string that is the name of the function and ($variable arg1 arg2 ...) calls the function passing the arguments. See below:

function x(){    echo $3 $1 $2      <== just rearrange the order of passed params}Z="x"        # or just Z=x($Z  10 20 30)

gives: 30 10 20, where we executed the function named "x" stored in variable Z and passed parameters 10 20 and 30.

Above where we reference functions by assigning variable names to the functions so we can use the variable in place of actually knowing the function name (which is similar to what you might do in a very classic function pointer situation in c for generalizing program flow but pre-selecting the function calls you will be making based on command line arguments).

In bash these are not function pointers, but variables that refer to names of functions that you later use.


there's no need to use eval

function x() {  echo "Hello world"}function around() {  echo "before"  var=$($1)  echo "after $var"}around x