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'
}
From my comment on another answer (which I keep missing when I come back to this page)
This tells you if it exists, but not that it's a function
Dredging up an old post ... but I recently had use of this and tested both alternatives described with :
this generated :
declare is a helluvalot faster !
I think you're looking for the 'type' command. It'll tell you whether something is a function, built-in function, external command, or just not defined. Example:
It is possible to use 'type' without any external commands, but you have to call it twice, so it still ends up about twice as slow as the 'declare' version:
Plus this doesn't work in POSIX sh, so it's totally worthless except as trivia!
If declare is 10x faster than test, this would seem the obvious answer.
Edit: Below, the
-f
option is superfluous with BASH, feel free to leave it out. Personally, I have trouble remembering which option does which, so I just use both. -f shows functions, and -F shows function names.The "-F" option to declare causes it to only return the name of the found function, rather than the entire contents.
There shouldn't be any measurable performance penalty for using /dev/null, and if it worries you that much:
Or combine the two, for your own pointless enjoyment. They both work.