Is it possible to implement anonymous functions in bash (even when using eval if necessary)?

Since bash does not have first-class functions, I mimic anonymous functions by passing a string to a function, which is then evaluated by eval .

 it() { echo "$1" # prints the description of the spec beforeEach # a setup function eval "$2" if (($? == 0)); then # do something fi afterEach # a cleanup function } it "should echo something" '{ echo "something" }' 

This allows you to write very concise tests (it defines the specification). Now I am wondering if this is a valid use of eval.

EDIT

I know that opening {and closing} is not needed in an anonymous function string, just like that it looks like something like Jasmine.

EDIT

pseudo anonymous function is actually a test, which means that at the end of the test there is something like

 [[ var == 'foo' ]] 

or

 ((i > 10)) 

i.e. some kind of test (or argue in terms of XUnit). He never needs to return anything but a return code, which is then evaluated, and if the return code is 0 (success), the description is printed in green, otherwise in red (test failed).

+4
source share
3 answers

If he does his job, and you (and ideally others) understand how it works, absolutely.

I write similar code to automate test cases more than once or twice, but I admit that it can get quite hairy, especially if you start simple and then let it grow organically.

For what it's worth, I would suggest a stylistic improvement;

 if eval "$2"; then # something 

or if "something" is a simple command, a plain old

 eval "$2" && # something 

Having said that, it would be better if you could avoid eval at all, but it depends on your test cases.

 $2 && # something 
+1
source

I do not think this is the right example for eval. Anonymous functions are useful in several cases: closures , Currying, and callbacks come to mind (alliteration is unintentional). This implementation does not give you any of these permissions, since your pseudo-functions eval'ed still cannot return a value (other than exit status 0-255) and definitely cannot return another anonymous function.

+3
source

For one-time โ€œanonymousโ€ functions, I use the following convention to execute bash scripts in the function area:

 #!/usr/bin/env bash _() { #... } && _ " $@ " unset -f _ 

Although this is not anonymous, it is similar to the IIFE (Immediately Invoked Function) expression in JavaScript.

Bash functions must have a name. You can use whatever name you like ( main is a popular choice.) I prefer the single underscore _ because a) it is short and b) it is traditionally used in many languages โ€‹โ€‹to indicate the value of throwaway.

+2
source

Source: https://habr.com/ru/post/1432707/


All Articles