目前我正在做一些单元测试,这些单元测试是从bash执行的。单元测试是在bash脚本中初始化、执行和清理的。此脚本通常包含init()、execute()和cleanup()函数。但它们不是强制性的。我想测试一下是否定义了它们。
我之前通过贪婪和seding源代码做到了这一点,但这似乎是错误的。有没有更优雅的方式来做这件事?
编辑:下面的代码片段很有吸引力:
fn_exists()
{
LC_ALL=C type $1 | grep -q 'shell function'
}
发布于 2008-09-17 18:00:15
像这样:[[ $(type -t foo) == function ]] && echo "Foo exists"
内置的type
命令将告诉您某些东西是函数、内置函数、外部命令还是未定义的。
其他示例:
$ LC_ALL=C type foo
bash: type: foo: not found
$ LC_ALL=C type ls
ls is aliased to `ls --color=auto'
$ which type
$ LC_ALL=C type type
type is a shell builtin
$ LC_ALL=C type -t rvm
function
$ if [ -n "$(LC_ALL=C type -t rvm)" ] && [ "$(LC_ALL=C type -t rvm)" = function ]; then echo rvm is a function; else echo rvm is NOT a function; fi
rvm is a function
发布于 2008-09-17 18:04:14
内置bash命令declare
有一个选项-F
,用于显示所有已定义的函数名。如果给定了名称参数,它将显示这些函数中存在的函数,如果所有函数都存在,它将相应地设置状态:
$ fn_exists() { declare -F "$1" > /dev/null; }
$ unset f
$ fn_exists f && echo yes || echo no
no
$ f() { return; }
$ fn_exist f && echo yes || echo no
yes
发布于 2012-01-25 19:34:09
借鉴其他解决方案和评论,我得出了以下结论:
fn_exists() {
# appended double quote is an ugly trick to make sure we do get a string -- if $1 is not a known command, type does not output anything
[ `type -t $1`"" == 'function' ]
}
用作...
if ! fn_exists $FN; then
echo "Hey, $FN does not exist ! Duh."
exit 2
fi
它检查给定的参数是否是函数,并避免重定向和其他返回值。
https://stackoverflow.com/questions/85880
复制相似问题