≡ Menu

Bash Shell: Check If A Function Exists Or Not (Find Out If a Function Is Defined Or Not)

How do I determine if a function called foo() is already defined in a bash script or not? If a function called foo() is defined just call it or show an error message?

You can use the following builtins to determine if a function is defined or not:

type builtin example

Create a function called foo():

foo(){ echo "Hello"; }

Find out if foo is defined or not:

type foo &>/dev/null && echo "foo() found." || echo "foo() not found."

Call foo if defined, enter:

type foo &>/dev/null && foo

declare builtin example

Create a function called bar():

bar(){ echo "Hello, World."; }

Find out if bar is defined or not:

declare -F bar &>/dev/null && echo "bar() found." || echo "bar() not found."

Call bar() if defined, enter:

declare -F bar && bar

Here is a sample code from one of my working code:

	local d="${_JAIL_DIR:-/nginx}"
        # remove / from each etc/file and build jail specific paths 
	local _passwd="${d}${_passwddb#/}"
	local _shadow="${d}${_shadowdb#/}"
	local _group="${d}${_groupsdb#/}"
	local _hosts="${d}${_hostsdb#/}"
	echo 'root:x:0:0:root:/root:/bin/bash' >${_passwd}
	grep "^{$_nginx_user}" ${_passwddb} >>${_passwd} 
	echo 'root:!!:14611:0:99999:7:::' >${_shadow}
	grep "^{$_nginx_user}" ${_shadowdb}  >>${_shadow}
	egrep "root|{$_nginx_group}" ${_groupsdb} >${_group}
        # Call __patch_etc_hosts_file() only if it is defined.
        # Patch /etc/hosts in $d jail, this is a system specific and should be added 
        # in $BASEDIR/hooks.sh (see /usr/local/nixcraft/docs/nginx.README.txt for more info)
	declare -F __patch_etc_hosts_file &>/dev/null && __patch_etc_hosts_file

See also:

See man pages:
man bash
help type
help declare

Share this tutorial on:

Like this? Follow us on Twitter OR support us by using Patreon

{ 4 comments… add one }
  • Philippe Petrinko April 1, 2010, 10:13 pm

    typo Here ?
    declare -F bar && ba
    should be
    declare -F bar && bar

  • nixCraft April 2, 2010, 6:47 am

    Thanks Philippe!

    There is a bug in pre bash html syntax wordpress and it eats last or first character some time.

  • Nilesh April 3, 2010, 7:27 am

    Nice one. A must for good scripting.

    Explore Technology

  • Sundeep Borra July 14, 2010, 10:59 am

    Great info, Thanks for the tip

Security: Are you a robot or human?

Leave a Comment

You can use these HTML tags and attributes: <strong> <em> <pre> <code> <a href="" title="">

   Tagged with: , , , , , , , , ,