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

last updated in Categories , ,

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/ (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


Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

4 comment

  1. Thanks Philippe!

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

    Still, have a question? Get help on our forum!