linuxbashenvironment-variablessetenvshellshock-bash-bug

Set a Bash function on the environment


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

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

Or equivalent from a C program:

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

Or

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

But using a Bash version with shellshock fixed, I can't manage on how to define my functions in the environment.

The strange thing is, if I run env, I can see my function defined in the environment, but if I call it, Bash says that it doesn't exist.

Thanks in advance


Solution

  • If you are invoking bash with execv (so that you are only invoking it once), you could replace (using execl for explanatory purposes):

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

    with

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

    and then you don't need to play games with the internal bash interface for defining functions. (If the bash script being run also needs the functions to be exported, for whatever reason, just add export -f <func> lines to the argument following -c.)

    That has the advantage of working with both patched and unpatched bashes.

    (I'm having to make a similar patch to various programs, so I share your pain.)