用bash测试一个程序
我用c编写了一个程序,现在我有一个二进制文件.我还为测试生成了一堆测试.现在我想用bash自动化测试过程.我想在我的二进制文件的一次执行中保存三件事:
>执行时间 现在我正在堆叠一个脚本,该脚本只测试二进制文件执行其工作并返回0并且不保存我上面提到的任何信息.我的脚本看起来像这样 #!/bin/bash if [ "$#" -ne 2 ]; then echo "Usage: testScript <binary> <dir_with_tests>" exit 1 fi binary="$1" testsDir="$2" for test in $(find $testsDir -name '*.txt'); do testname=$(basename $test) encodedTmp=$(mktemp /tmp/encoded_$testname) decodedTmp=$(mktemp /tmp/decoded_$testname) printf 'testing on %s...n' "$testname" if ! "$binary" -c -f $test -o $encodedTmp > /dev/null; then echo 'encoder failed' rm "$encodedTmp" rm "$decodedTmp" continue fi if ! "$binary" -u -f $encodedTmp -o $decodedTmp > /dev/null; then echo 'decoder failed' rm "$encodedTmp" rm "$decodedTmp" continue fi if ! diff "$test" "$decodedTmp" > /dev/null ; then echo "result differs with input" else echo "$testname passed" fi rm "$encodedTmp" rm "$decodedTmp" done 我想在变量中保存$binary的输出,而不是将其发送到/ dev / null.我还想使用时间bash功能节省时间 解决方法
当您要求将输出保存在shell变量中时,我尝试不使用输出重定向来回答这个问题 – 这会将输出保存在(临时)文本文件中(然后必须将其清除).
保存命令输出 你可以替换这一行 if ! "$binary" -c -f $test -o $encodedTmp > /dev/null; then 同 if ! output=$("$binary" -c -f $test -o $encodedTmp); then 使用命令替换将$binary的程序输出保存在shell变量中.命令替换(与shell变量赋值相结合)也允许程序的退出代码传递给调用shell,因此条件if语句将继续检查$binary是否执行而没有错误. 您可以通过运行echo“$output”来查看程序输出. 节省时间 如果没有更复杂的进程间通信形式,那么另一个shell的子进程的shell就无法改变其父进程的变量或环境,这是我可以节省时间和程序的唯一方法输出是将它们组合在一个变量中: if ! time-output=$(time "$binary" -c -f $test -o $encodedTmp) 2>&1); then 由于时间将其分析信息打印到stderr,我使用括号运算符在子shell中运行命令,其stderr可以重定向到stdout.编程输出和时间输出可以通过运行echo“$time-output”查看,它应返回类似于: <program output> <blank line> real 0m0.041s user 0m0.000s sys 0m0.046s (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |