Test for function's existence that can work on both bash and zsh?

5,471

Solution 1

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.

Solution 2

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
Share:
5,471

Related videos on Youtube

kjo
Author by

kjo

Updated on September 18, 2022

Comments

  • kjo
    kjo almost 2 years

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

  • muru
    muru over 7 years
    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.
  • Sagar
    Sagar over 7 years
    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.