Passing a code block as an anon. function
I've managed to do what you want with a eval
hack.
With this I lay warned that eval is insecure and you should avoid at all costs. Having that said, if you trust your code won't be abused, you can use this:
wrap_this(){
run_something
eval "$(cat /dev/stdin)"
run_something_else
}
This allows you to run code as follows:
wrap_this << EOF
my function
EOF
Not exactly ideal, since the inner block is a string, but does create reuse.
No, bash doesn't have anonymous functions. It is however possible to pass a function name and arguments as strings and have bash call it.
function wrap() {
do_before
"$@"
do_after
}
wrap do_something with_arguments
This is however, somewhat limited. Dealing with quoting can become a problem. Passing more than one command is also a complication.
You can put code in a string and pass it to eval
or sh
or simply interpolate it.
perform () {
"$@"
}
perform echo "moo"
You can quickly end up in deep quoting trouble, though.