19

Is there a way to test whether a shell function exists that will work both for bash and zsh?

2 Answers 2

28

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.

0
4

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
2
  • 4
    This would also succeed if foo was an alias or an existing command instead of a function ... which may or may not matter depending on what OP intends to do with the function.
    – muru
    Dec 22, 2016 at 3:01
  • 1
    well of course you can add type foo | grep "foo.*function". The bash shell will print the function definition as well. zsh shell will simply inform type is function.
    – Sagar
    Dec 22, 2016 at 3:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .