joshuatvernon joshuatvernon - 7 months ago 14
Bash Question

How to output 'passed' if a diff command results in no difference in bash?

I am writing a shell script that loops over my ./tests directory and uses the unix diff command to compare .in and .out files against each other for my C program. Here is my shell script:

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


My question is how can I add an if statement to the script that will output 'passed' if the diff command results in no difference? e.g.

pseudo code:

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

Answer

Get and check the exit code from the diff command. diff has an exit code of 0 if no differences were found.

diff ...
ret=$?

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