Currently I'm doing some unit tests which are executed from bash. Unit tests are initialized, executed and cleaned up in a bash script. This script usualy contains an init(), execute() and cleanup() functions. But they are not mandatory. I'd like to test if they are or are not defined.
I did this previously by greping and seding the source, but it seemed wrong. Is there a more elegant way to do this?
Edit: The following sniplet works like a charm:
fn_exists()
{
LC_ALL=C type $1 | grep -q 'shell function'
}
I particularly liked solution from Grégory Joseph
But I've modified it a little bit to overcome "double quote ugly trick":
update
Testing different solutions:
outputs e.g.:
So
declare -F f
seems to be the best solution.It boils down to using 'declare' to either check the output or exit code.
Output style:
Usage:
However, if memory serves, redirecting to null is faster than output substitution (speaking of, the awful and out-dated `cmd` method should be banished and $(cmd) used instead.) And since declare returns true/false if found/not found, and functions return the exit code of the last command in the function so an explicit return is usually not necessary, and since checking the error code is faster than checking a string value (even a null string):
Exit status style:
That's probably about as succinct and benign as you can get.
I would improve it to:
And use it like this: