bash - 确定函数是否存在于 bash 中

标签 bash function testing scripting

目前我正在做一些从 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/

相关文章:

linux - Bash变量扩展不能与时间命令结合使用

regex - 删除 2 个匹配模式之间的 n 行,保留第一个匹配项并删除第二个匹配项

python - 我们可以使用外部函数在python的外部函数范围之外访问内部函数吗?

javascript - 在附加到对象属性的 javascript 函数中使用 'this'

php - Laravel 4.1 - 使用 Phpunit 和 Mockery 测试 Artisan 命令

testing - Geb(自动化测试框架)是一个好的验收测试框架吗?

linux - 用于查找文件中每个字母出现频率的 Bash 脚本

regex - 仅从 CSV 的第二个字段中删除 ":"并忽略其他字段

excel - 每 6 行将单元格引用增加 1

xml - 如何在 arquillian.xml 中正确地向 ChromeDriver 添加配置文件和扩展