Skip to content
Latchkey

diff -u: Unified Diffs Between Two Files

diff -u compares two files and prints the differences as a unified diff with a few lines of surrounding context.

The unified format is the lingua franca of patches. In CI, diff is most useful for its exit code: 0 means identical, 1 means they differ.

What it does

diff compares two files line by line. With -u it emits a unified diff: a header naming both files, then @@ hunks with a leading - for removed lines and + for added lines. Exit status is 0 if the files are identical, 1 if they differ, and 2 on trouble (missing file).

Common usage

Terminal
diff -u expected.txt actual.txt
diff -u <(sort a.txt) <(sort b.txt)
# compare a committed file against freshly generated output
mytool generate > generated.new
diff -u generated.txt generated.new

Options

FlagWhat it does
-uOutput a unified diff (3 lines of context by default)
-U <n>Unified diff with n lines of context
-cOutput an old-style context diff instead
-wIgnore all whitespace
-bIgnore changes in the amount of whitespace
-iIgnore case differences

In CI

diff -u is the cheapest way to fail a job when generated output drifts. Generate the file, diff it against the checked-in copy, and let the exit code fail the step: diff -u committed.txt generated.txt. For an explicit gate that only cares about the code, see diff --exit-code.

Common errors in CI

"diff: No such file or directory" (exit 2) means one path is wrong, not that the files differ; treat exit 2 differently from exit 1. A nonzero exit that surprises you is usually the point: exit 1 means differences were found, which is exactly what a staleness gate should fail on. Trailing-newline-only differences show as "\ No newline at end of file".

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →