Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous functions in shell scripts

Tags:

bash

shell

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.

like image 551
Matty Avatar asked Dec 08 '11 08:12

Matty


People also ask

How do you use anonymous function?

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 () .

Can we have function without name bash?

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.

Can Lambda run shell scripts?

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.


2 Answers

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.

like image 79
Ignacio Vazquez-Abrams Avatar answered Sep 20 '22 23:09

Ignacio Vazquez-Abrams


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.

like image 26
Spencer Tipping Avatar answered Sep 20 '22 23:09

Spencer Tipping