Bash Shell:检查功能是否存在(查找是否定义了功能)
时间:2020-01-09 10:37:27 来源:igfitidea点击:
如何确定bash脚本中是否已定义名为foo()的函数?
如果定义了一个名为foo()的函数,只需调用它或显示错误消息?
您可以使用以下内置函数来确定是否定义了函数:
type内置命令显示有关命令类型的信息。declare内置命令设置或显示变量信息。
内置命令type 示例
创建一个名为foo()的函数:
foo(){ echo "Hello"; }
找出是否定义了foo:
type foo &>/dev/null && echo "foo() found." || echo "foo() not found."
调用foo(如果已定义),输入:
type foo &>/dev/null && foo
内置命令declare 示例
创建一个名为bar()的函数:
bar(){ echo "Hello, World."; }
找出是否定义了bar:
declare -F bar &>/dev/null && echo "bar() found." || echo "bar() not found."
调用bar()(如果已定义),输入:
declare -F bar && bar
这是我的一个工作代码中的示例代码:
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/theitroad/docs/nginx.README.txt for more info)
declare -F __patch_etc_hosts_file &>/dev/null && __patch_etc_hosts_file
}

