Determine if a function exists in bash Determine if a function exists in bash bash bash

Determine if a function exists in bash


Like this: [[ $(type -t foo) == function ]] && echo "Foo exists"

The built-in type command will tell you whether something is a function, built-in function, external command, or just not defined.

Additional examples:

$ LC_ALL=C type foobash: type: foo: not found$ LC_ALL=C type lsls is aliased to `ls --color=auto'$ which type$ LC_ALL=C type typetype is a shell builtin$ LC_ALL=C type -t rvmfunction$ if [ -n "$(LC_ALL=C type -t rvm)" ] && [ "$(LC_ALL=C type -t rvm)" = function ]; then echo rvm is a function; else echo rvm is NOT a function; firvm is a function


The builtin bash command declare has an option -F that displays all defined function names. If given name arguments, it will display which of those functions are exist, and if all do it will set status accordingly:

$ fn_exists() { declare -F "$1" > /dev/null; }$ unset f$ fn_exists f && echo yes || echo nono$ f() { return; }$ fn_exist f && echo yes || echo noyes


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.

#!/bin/shfunction_exists() {    declare -f -F $1 > /dev/null    return $?}function_exists function_name && echo Exists || echo No such function

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:

fname=`declare -f -F $1`[ -n "$fname" ]    && echo Declare -f says $fname exists || echo Declare -f says $1 does not exist

Or combine the two, for your own pointless enjoyment. They both work.

fname=`declare -f -F $1`errorlevel=$?(( ! errorlevel )) && echo Errorlevel says $1 exists     || echo Errorlevel says $1 does not exist[ -n "$fname" ]    && echo Declare -f says $fname exists || echo Declare -f says $1 does not exist