C 如果diff命令在bash中不产生任何差异,如何输出“passed”?

C 如果diff命令在bash中不产生任何差异,如何输出“passed”?,c,shell,testing,automated-tests,diff,C,Shell,Testing,Automated Tests,Diff,我正在编写一个shell脚本,它在./tests目录上循环,并使用unix diff命令为我的C程序比较.in和.out文件。以下是我的shell脚本: #! /usr/bin/env bash count=0 # Loop through test files for t in tests/*.in; do echo '================================================================' echo '

我正在编写一个shell脚本,它在./tests目录上循环,并使用unix diff命令为我的C程序比较.in和.out文件。以下是我的shell脚本:

#! /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

从diff命令获取并检查退出代码。如果未发现差异,则diff的退出代码为0

diff ...
ret=$?

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

@jstills的答案对我来说很有用,但我对它做了一些修改,并认为我应该把我的结果也作为一个答案发布,以帮助其他人

一旦我了解到diff的退出代码是0,我就将代码修改为0。如果我理解正确,它会检查每个差异是否以0或>1退出。然后,我的代码将diff的输出发送到/dev/null,这样它就不会显示到stdout,然后我进行检查并将通过或失败的结果打印到stdout,如果失败,则使用sdiff打印差异,sdiff并排显示差异

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

我在某个地方读到过,for循环不应该用于遍历目录中的文件。但是我想不起来在哪里。你知道为什么或者应该使用什么工具来代替吗?我读的文章建议使用while循环。但是你可以忽略这些评论,除非有人确认或者我能找到答案source@sjsam你的意思是?“因为和地球是好的,”本杰明说。;你搞定了。。这是我一直在搜索的内容…您可能希望将>/dev/null更改为>/dev/null 2>&1。在当前场景中,差异错误仍将转储到标准输出。请参阅添加到我的脚本中的@sjsam Good addition。
if diff "${t%.*}.res" "${t%.*}.out" >/dev/null; then
    printf "Passed\n"
else
    printf "Failed\n"
    sdiff "${t%.*}.res" "${t%.*}.out"
fi