views:

58

answers:

3

Hi,

I am writing a bash script to run an integration test of a tool I am writing.

Basically I run the application with a set of inputs and compare the results with expected values using the diff command line tool.

It's working, but I would like to enhance it by knowing the result of the diff command and print "SUCCESS" or "FAIL" depending on the result of the diff.

How can I do it?

+3  A: 

The $? variable holds the result of the last executed command.

Richard Mar.
+3  A: 
if diff file1 file2; then
    echo Success
else
    echo Fail
fi

If both files are equal, diff returns 0, which is the return code for if to follow then. If file1 and file2 differ, diff returns 1, which makes if jump to the else part of the construct.

You might want to suppress the output of diff by writing diff file1 file2 >/dev/null instead of the above.

exic
I think you should make clear how exactly it works
LukeN
Thanks, this worked for me. I had read about $? variable, but I wasn't sure how Diff used it. Thanks. Does anyone know if it's possible to diff all files from a directory with another?I have tried diff dir1/* dir2/* but it didn't work.
Fork
diff -R dir1 dir2
Joshua
LukeN: Thanks for the hint, I added an explanation.Fork: I’m glad it worked for you. To diff directories, use the -r (recursive) switch: diff -r dir1 dir2
exic
A: 

Also, in Bash you can diff the outputs of commands directly using process substitution:

if diff <(some_command arg1) <(some_command arg1) > /dev/null 2>&1
then
    echo "They're the same."
else
    echo "They're different."
fi
Dennis Williamson