【发布时间】:2012-10-10 09:09:05
【问题描述】:
我有一个 shell 脚本,我想用 shUnit 进行测试。脚本(和所有函数)都在一个文件中,因为它使安装更加容易。
script.sh 的示例
#!/bin/sh
foo () { ... }
bar () { ... }
code
我想写第二个文件(不需要分发和安装)来测试script.sh中定义的功能
类似run_tests.sh
#!/bin/sh
. script.sh
# Unit tests
现在问题在于.(或Bash 中的source)。它不仅解析函数定义,还执行脚本中的代码。
由于没有参数的脚本没有任何坏处,我可以
. script.sh > /dev/null 2>&1
但是如果有更好的方法来实现我的目标,我正在徘徊。
编辑
如果源脚本调用exit,我建议的解决方法不起作用,所以我必须捕获出口
#!/bin/sh
trap run_tests ERR EXIT
run_tests() {
...
}
. script.sh
run_tests 函数被调用,但是一旦我重定向源命令的输出,脚本中的函数就不会被解析并且在陷阱处理程序中不可用
这可行,但我得到了script.sh 的输出:
#!/bin/sh
trap run_tests ERR EXIT
run_tests() {
function_defined_in_script_sh
}
. script.sh
这不会打印输出,但我收到一个错误,指出函数未定义:
#!/bin/sh
trap run_tests ERR EXIT
run_tests() {
function_defined_in_script_sh
}
. script.sh | grep OUTPUT_THAT_DOES_NOT_EXISTS
这不会打印输出,并且根本不会调用 run_tests 陷阱处理程序:
#!/bin/sh
trap run_tests ERR EXIT
run_tests() {
function_defined_in_script_sh
}
. script.sh > /dev/null
【问题讨论】:
标签: shell