如果diff命令导致bash无差异,如何输出'passed'?

问题描述:

我正在编写一个shell脚本,它遍历我的./tests目录并使用unix diff命令将我的C程序中的.in和.out文件相互比较。这里是我的shell脚本:如果diff命令导致bash无差异,如何输出'passed'?

#! /usr/bin/env bash 

count=0 

# Loop through test files 
for t in tests/*.in; do 
echo '================================================================' 
echo '       Test' $count 
echo '================================================================' 
echo 'Testing' $t '...' 

# Output results to (test).res 
(./snapshot < $t) > "${t%.*}.res" 

# Test with diff against the (test).out files 
diff "${t%.*}.res" "${t%.*}.out" 

echo '================================================================' 
echo '       Memcheck 
echo '================================================================' 

# Output results to (test).res 
(valgrind ./snapshot < $t) > "${t%.*}.res" 

count=$((count+1)) 

done 

我的问题是我怎么能if语句添加到要输出“通过”脚本如果没有差异diff命令的结果吗?例如

伪代码:

if ((diff res_file out_file) == '') { 
    echo 'Passed' 
} else { 
    printf "Failed\n\n" 
    diff res_file out_file 
} 
+0

我已经阅读过某处,for循环不应该用于遍历目录中的文件。但不记得在哪里。 – sjsam

+0

你知道为什么或者什么是合适的工具来使用吗? – joshuatvernon

+0

我读的文章建议使用while循环。但是你可能会忽略这些评论,除非有人确认或者我能够找到源码 – sjsam

获取和diff命令检查退出代码。如果没有找到差异,则diff的退出代码为0。

diff ... 
ret=$? 

if [[ $ret -eq 0 ]]; then 
    echo "passed." 
else 
    echo "failed." 
fi 

通过@jstills答案为我工作,但是我修改了它稍微我想我会后我的结果作为答案也帮助别人

一旦我了解,DIFF有退出代码0我修改了我的代码。如果我理解正确,它会检查diff是否以0或> 1的差距退出。然后,我的代码将diff的输出发送到/ dev/null,因此它不会显示到stdout,然后执行我的检查并打印通过或未通过stdout,并且如果与sdiff的差异并排显示,则失败。

if diff "${t%.*}.res" "${t%.*}.out" >/dev/null; then 
    printf "Passed\n" 
else 
    printf "Failed\n" 
    sdiff "${t%.*}.res" "${t%.*}.out" 
fi 
+1

你可能希望改变'>/dev/null'到'>/dev/null 2>&1'。在当前情况下,diff错误仍然会被转储到stdout。见[this](http://www.cyberciti.biz/faq/how-to-redirect-output-and-errors-to-devnull/) – sjsam

+0

@sjsam很好的补充,加到我的脚本中。 – joshuatvernon