joshuatvernon
joshuatvernon

Reputation: 1621

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
}

Upvotes: 2

Views: 6634

Answers (2)

joshuatvernon
joshuatvernon

Reputation: 1621

The answer by @jstills worked for me however I modified it slightly and thought I'd post my result as an answer too to help others

Once I understood that diff has an exit code of 0 I modified my code to this. It checks if diff exits with 0 or >1 for each difference if I understand correctly. My code then sends the output of diff to /dev/null so it won't be displayed to stdout and I then do my check and print passed or failed to the stdout and if failed the differences with sdiff which display differences side by side.

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

Upvotes: 2

Jstills
Jstills

Reputation: 326

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

Upvotes: 6

Related Questions