Test for function's existence that can work on both bash and zsh?
If you want to check that there's a currently defined (or at least potentially marked for autoloading) function by the name foo
regardless of whether a builtin/executable/keyword/alias may also be available by that name, you could do:
if typeset -f foo > /dev/null; then
echo there is a foo function
fi
Though note that if there's a keyword or alias called foo
as well, it would take precedence over the function (when not quoted).
The above should work in ksh
(where it comes from), zsh
and bash
.
This is pure POSIX, so it should work on all POSIX shells.
foo()
{
echo "bar"
}
if type 'foo' 2>/dev/null | grep -q 'function'
then
echo 'function exists'
fi