As bash doesn't have first class functions, I'm simulating anonymous functions by passing a string to a function, which then gets 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 to write very concise tests (it defines a specification). Now I wonder if this is a valid use of eval.
EDIT
I am aware that the opening { and closing } are not need in the anonymous function string, it's just that that way it resembles for something like Jasmine.
EDIT
The pseudo anonymous function
is actually a test, which means at the end of the test, there is something like
[[ var == 'foo' ]]
or
((i > 10))
i.e. some sort of test (or assert, in XUnit terms). It never needs to return anything than the return code which then gets evaluated, and if the return code is 0 (success), the description is printed in green, otherwise red (the test failed).
The advantage of an anonymous function is that it does not have to be stored in a separate file. This can greatly simplify programs, as often calculations are very simple and the use of anonymous functions reduces the number of code files necessary for a program.
Complete answer: Functions in bash are not first-class objects, therefore there can be no such thing as an anonymous function in bash.
An anonymous function is not accessible after its initial creation, it can only be accessed by a variable it is stored in as a function as a value. 3. This function is useful for all scenarios. An anonymous function can be useful for creating IIFE(Immediately Invoked Function Expression).
An anonymous function is a function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation. Normal function definition: function hello() { alert('Hello world'); } hello();
For one-time-use "anonymous" functions, I use the following convention to execute bash scripts in a function scope:
#!/usr/bin/env bash
_() {
#...
} && _ "$@"
unset -f _
Although not truly anonymous, this is similar to the IIFE (Immediately-Invoked Function Expression) idiom in JavaScript.
Bash functions must have a name. You can use any name you like (main
is a popular choice.) I prefer a single underscore _
because a) it's short and b) it's conventionally used in many languages to indicate a throwaway value.
I don't think it is a valid case for eval. Anonymous functions are useful in a few cases: closures, Currying, and callbacks come to mind (alliteration unintended). This implementation gives you none of those powers, since your eval'ed pseudo-functions still can't return a value (other than a 0-255 exit status), and definitely can't return another anonymous function.
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