Bohr
Bohr

Reputation: 1716

How to define a function to create functions in bash?

If a simple function factory is possible in bash?

For example: function_factory func1 func2 func3 will create three functions that just have the passed names without doing anything.

These birthed functions should be exported with like export -f function_name to make sure they are available in the same environment of function_factory .

Upvotes: 2

Views: 268

Answers (3)

glenn jackman
glenn jackman

Reputation: 246744

This is about as minimal as I can get:

factory() { for f; do eval "$f() { :; }"; done; }

Then:

$ factory f{1..3}
$ type f1 f2 f3 f4
f1 is a function
f1 () 
{ 
    :
}
f2 is a function
f2 () 
{ 
    :
}
f3 is a function
f3 () 
{ 
    :
}
bash: type: f4: not found

Upvotes: 0

loentar
loentar

Reputation: 5239

It could be something like that:

#!/bin/bash

function function_factory()
{
  while [ $# -ne 0 ]
  do
    eval "
    function $1()
{
  echo \"my name is $1\"
}
"
    shift
  done
}

function_factory fun1 fun2 fun3

fun1
fun3

output:

$ ./test 
my name is fun1
my name is fun3

Upvotes: 0

Jiaming Lu
Jiaming Lu

Reputation: 885

Maybe you can use eval:

function generate_hello {
  eval "function say_hello_to_$1 { echo hello $1; }"
}

Then run it:

$ generate_hello world
$ say_hello_to_world
hello world

Upvotes: 1

Related Questions