目前我正在做一些从 bash 执行的单元测试。单元测试在 bash 脚本中初始化、执行和清理。该脚本通常包含 init()、execute() 和 cleanup() 函数。但它们不是强制性的。我想测试它们是否已定义。
我之前通过 greping 和 seding 源来做到这一点,但这似乎是错误的。有没有更优雅的方法来做到这一点?
编辑:下面的代码片段很有魅力:
fn_exists()
{
LC_ALL=C type $1 | grep -q 'shell function'
}
最佳答案
像这样:[[ $(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
关于bash - 确定函数是否存在于 bash 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/85880/