Unix Power Tools

Context diffs

The output of diff -e shows compact formats with just the differences between the files.
But, in many cases, context diff listings are more useful.
Context diffs show the changed lines and the lines around them.
(This can be a headache if you're trying to read the listing on a
terminal and there are many changed lines fairly close to one another:
the context will make a huge "before" section, with the "after" section
several screenfuls ahead.
In that case, the more compact diff formats can be useful.)

On many versions of diff (including the GNU version used on Linux), the -c option shows context around each change.
By itself, -c shows three lines above and below each change.
Here's an example of a C++ file before and after some edits; the -c2
option shows two lines of context:

The listing starts with the two filenames and their last-modified dates
("timestamps").
The first filename (here, include.h.orig) has three asterisks
(***) before it; the second name has three dashes (---).
These markers identify the two files in the difference listings below.

Each changed section starts with a long row of asterisks.
Next comes a range of lines from the first file and the line numbers shown
in that section (marked with a pair of triple asterisks around the line
numbers).
After the first file's section, a similar section shows the changed version
in the second file, marked with a pair of triple dashes around the line
numbers.

Changed lines that exist in both files are marked with an ! (exclamation point)
character in the left margin.
So, two of the lines between lines 45-52 were changed.
include.h.orig had the line Node *last;;
in include.h, part of that line was changed to read Node *tail;.
The pair of lines starting with void load were also changed.
Other lines in the section weren't changed.

The next changed section shows lines 77-84 in include.h.orig and
77-85 in include.h.
The minus sign (-) in the left margin shows that the
int boundary line of include.h.orig was deleted; it
doesn't appear in the second file.
In the second file, include.h, there are two new lines -- marked with a
plus sign (+) in the margin.

Context diffs aren't just nice for reading.
The
patch
program reads context diff listings and uses them to update files
automatically.
For example, if I had include.h.orig, someone could send me the
diff listing above (called a "patch").
From the original and the patch, patch could create include.h.
The advantage of a context diff over the more compact -e format is that context diffs let patch locate the changed sections
even if they've been moved somewhat.