Is it possible to create something analogous to an anonymous function whose value can be assigned to an array element and later called? I can't seem to find a way to do this in a bash script but perhaps there's a workaround.
The () makes the anonymous function an expression that returns a function object. An anonymous function is not accessible after its initial creation. Therefore, you often need to assign it to a variable. In this example, the anonymous function has no name between the function keyword and parentheses () .
Short answer: No. Long answer: Nooooooooooooo. Complete answer: Functions in bash are not first-class objects, therefore there can be no such thing as an anonymous function in bash.
AWS recently announced the "Lambda Runtime API and Lambda Layers", two new features that enable developers to build custom runtimes. So, it's now possibile to directly run even bash scripts in Lambda without hacks.
Short answer: No.
Long answer: Nooooooooooooo.
Complete answer: Functions in bash are not first-class objects, therefore there can be no such thing as an anonymous function in bash.
It is possible; I wrote a library to do exactly this, though it's a very strange project. The source code is available at http://github.com/spencertipping/bash-lambda. Using this library:
$ my_array=() $ my_array[0]=$(fn x 'echo $((x + 1))') $ my_array[1]=$(fn x 'echo $((x + 2))') $ ${my_array[0]} 5 6 $ ${my_array[1]} 5 7 $
The trick is to have the fn
function create a file containing the body of the function, chmod +x
that file, then return its name. This causes stray files to accumulate, which is why the library also implements an asynchronous mark/sweep garbage collector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With