2016-04-22 68 views
0

我正在編寫一個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

回答

3

獲取和diff命令檢查退出代碼。如果沒有找到差異,則diff的退出代碼爲0。

diff ... 
ret=$? 

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

通過@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