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 && 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:
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.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.
🐧 4 comments so far... add one ↓
🐧 4 comments so far... add one ↓
Category | List of Unix and Linux commands |
---|---|
File Management | cat |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Network Utilities | dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • jobs • killall • kill • pidof • pstree • pwdx • time |
Searching | grep • whereis • which |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
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