2

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 .

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.