On the command line, after using diff on two files that differ, the command
echo $?
reports back '1'. When I try the same in a script, as follows:
echo "` diff $F1 $F2`"
rv=$?
if [[ $rv == 1 ]]
then
echo "failed"
fi
then I never print 'failed' (even for differing files). Note that this is the bash shell, so the grammar should be fine (eg, if I check for '0' instead, it always prints).
How can I check if the diff command discovered differences, and process conditionally on that?
This is under Ubuntu 12.04.
You're not seeing the return value from diff because the last command run is actually echo and you're seeing its return value. You should be able to achieve the desired effect with the following code (capturing and then echoing the output of diff is unnecessary - just let it write to stdout):
diff $F1 $F2
rv=$?
if [[ $rv == 1 ]]
then
echo "failed"
fi
Also, note that diff returns a value greater than one on error (0 indicates identical files, 1 indicates different files). You may want to check for and handle that case.
From your comment:
But I would like to print the differences first, but also keep track of how many comparisons failed.
I don't know if diff outputs the number of differences in the exit code. I think not. But you could count the lines maybe...
Here is how you can store the exit code and count the number of different lines
var=$(diff "$F1" "$F2")
#store diff exit code
exit_code=$?
# remember that this is not the same as count of differences
lines_output_by_diff=$(wc -l <<< "$var")
echo "$var"
if (($exit_code == 0)); then
echo "same"
else
echo "not same"
fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With