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 command - Display information about command type.
- declare builtin command - Set or display variables information.
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 && foodeclare 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:
patch_etc_files(){ 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
- Our Linux bash shell scripting guide.
You should follow me on twitter here or grab rss feed to keep track of new changes.
Featured Articles:
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012

- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop












{ 4 comments… read them below or add one }
typo Here ?
declare -F bar && ba
should be
declare -F bar && bar
Thanks Philippe!
There is a bug in pre bash html syntax wordpress and it eats last or first character some time.
Nice one. A must for good scripting.
Explore Technology
Great info, Thanks for the tip