I am reading this post on using functions in bash shell variables. I observe that to use shell functions, one has to export them and execute them in a child shell as follows:
$ export foo='() { echo "Inside function"; }'
$ bash -c 'foo'
Inside function
I want to ask whether it is possible for functions to be defined in bash shell variables such that they can be executed in the current shell without using export & running new shell ?
Best Answer
No, you can't.
If you want to use a function in current shell, just defining it then use it later:
Before Shellshock day, you can store function inside a variable, export variable and using function in sub-shell, because
bash
support exporting function,bash
will put function definition in environment variable like:then interpret the function by replace
=
with space. There's no intention for putting function in variable and refer to variable will executing the function.Now, after Stéphane Chazelas found the bug, that's feature was removed, no function definition stored in plain environment variable anymore. Now exported functions will be encoded by appending prefix
BASH_FUNC_
and suffix%%
to avoid clashed with environment variables.bash
interpreter can now determine whether or not they are shell function regardless of variables's content. You also need to define the function and export it explicitly to use it in sub-shell:Anyway, if your example worked with your current
bash
, then you are using a vulnerable version.