Set Bash function in environment

I need to define a Bash function in a Bash environment from a C / C ++ program. Before the shellshock error, I could define a function like this:

my_func='() { echo "This is my function";}'


Or the equivalent of a C program:

setenv("my_func", "() { echo \"This is my function\";}", 1);



putenv("my_func=() { echo \"This is my function\";}");


But using the Bash version with shellshock fix, I have no control over how my functions are defined in the environment.

Strangely, if I run env

I can see my function defined in the environment, but if I call it, Bash says it doesn't exist.

Thank you in advance


source to share

2 answers

If you call bash

with execv

(so you only call it once), you can replace (using execl

for clarification):

 execl("/bin/bash", "bash", "file_to_run", "arg1", "arg2", 0);



 execl("/bin/bash", "bash", "-c", "f() {...} g() {...}\n. $0",
                    "file_to_run", "arg1", "arg2", 0);


and then you don't have to play bash backend games to define functions. (If you run the bash script also the functions to be exported, for whatever reason, just add the lines export -f <func>

to the argument following -c


This has the advantage that it works with both fixed and unprepared databases.

(I need to make a similar patch for various programs, so I share your pain.)



For informational purposes only. Since it is not documented how functions are exported to the framework, you should consider this an abuse of the private API, which may change in future versions bash


Functions are no longer exported simply by using the function name on the environment string. To see this, run

$ my_func () { echo "foo"; }
$ export -f my_func
$ env | grep -A1 'my_func'
BASH_FUNC_my_func%%=() {  echo "foo"


Since the name used in the environment is no longer a valid identifier bash

, you will need to use the command env

to change the environment of the new process.

env 'BASH_FUNC_my_func%%=() { echo "This is my function"; }' bash


From C, you just need to customize the name.

setenv("BASH_FUNC_my_func%%", "() { echo \"This is my function\";}", 1);




All Articles