Ubuntu – exit code of diff

bash

If I run diff -q on two files and they are identical, the exit code generated by echo $? is 0; if the files differ, the exit code is 1. Why is that? In what way is the first diff a success and the second a failure?

I used the terms "success" and "failure" based on my reading and limited understanding of http://mywiki.wooledge.org/BashGuide/TestsAndConditionals:

  1. Exit Status
    Every command results in an exit code whenever it terminates.
    This exit code is used by whatever application started it to evaluate
    whether everything went OK. This exit code is like a return value from
    functions. It's an integer between 0 and 255 (inclusive). Convention
    dictates that we use 0 to denote success, and any other number to denote
    failure of some sort. The specific number is entirely application-specific,
    and is used to hint as to what exactly went wrong.

I should have read man diff right to the end where the convention used by the developers is clear.

Best Answer

From man diff:

Exit status is 0 if inputs are the same, 1 if different, 2 if trouble.

I freely admit this might not be completely standard but exit codes are more what you'd call "guidelines" than actual rules.

enter image description here

In this case, deviating from the standard allows you to easily run diff in scripts.

diff a b && echo "no difference" || echo "differences!"

This is similar to grep which will exit 0 is something is found, and 1 if something isn't found. I can't explain the orientation between 0 and 1 for diff. I assume they went with C-standard boolean outcomes.

It doesn't really matter. It's just an arbitrary number.