bash: How do I create function from variable?
You can use eval
:
eval "someprefix_${bname}() { echo test; }"
Bash even allows "."
s in function names :)
Indeed, it is instructive that the aforementioned construction derails the possibility of having embedded quotation marks there within and is thus potentially bugulant. However, the following construction does proffer similar functionality whilst not having the constraints of the former answer.
For your review:
source /dev/stdin <<EOF
function someprefix_${bname}()
{
echo "test";
};
EOF
The 'eval and 'source' solutions work IFF you do not have anything in the function that could be evaluated at create time that you actually want delayed until execution time.
source /dev/stdin << EOF
badfunc ()
{
echo $(date)
}
EOF
$ date;badfunc;sleep 10;date;badfunc
Tue Dec 1 12:34:26 EST 2015 ## badfunc output not current
Tue Dec 1 12:23:51 EST 2015
Tue Dec 1 12:34:36 EST 2015 ## and not changing
Tue Dec 1 12:23:51 EST 2015
Yes, it's a contrived example (just call date and don't echo a subshell call of it), but using the original answers, I tried something a more elaborate that required a run time evaluation and got similar results - evaluation at "compile" time, not run time.
The way that I solved the problem was to build a temp file with the function and then source that. By the judicious use of single and double quotes surrounding the test I print into the file, I can completely control what gets evaluated and when.
tmpsh=$(mktemp)
echo "goodfunc ()" > $tmpsh
echo '{' >> $tmpsh
echo 'echo $(date)' >> $tmpsh
echo '}' >> $tmpsh
. $tmpsh
rm -f $tmpsh
and then
$ date;goodfunc;sleep 10;date;goodfunc
Tue Dec 1 12:36:42 EST 2015 ## current
Tue Dec 1 12:36:42 EST 2015
Tue Dec 1 12:36:52 EST 2015 ## and advancing
Tue Dec 1 12:36:52 EST 2015
Hopefully, this will be of more use to people. Enjoy.