Skip to content
C.W.K.
Stream
Lesson 06 of 10 · published

diff: Comparing Files

~10 min · diff, patch, compare

Level 0Window Tourist
0 XP0/95 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

Spot every change between two files

diff a b shows the lines that differ between two files. The default output is terse and old-school. Add -u for the unified format git, GitHub, and code reviewers all use.

The flags you'll need

  • -u — unified diff with 3 lines of context (the standard).
  • -r — recursive across two directories.
  • -q — only say if files differ; don't show changes.
  • -i — ignore case.
  • -w — ignore all whitespace.
  • -B — ignore blank-line changes.
  • -y — side-by-side display.
  • --color=auto — color the diff (GNU diff 3.4+).

Reading a unified diff

Lines starting with - are in a only, + are in b only. The hunk header @@ -10,4 +10,5 @@ means "4 lines starting at line 10 in a, 5 lines starting at line 10 in b." Same format git diff uses.

Patches

Save a diff to a file: diff -u a b > change.patch. Apply it later: patch < change.patch. This is how Linux kernel patches travel by email.

Better than diff for code

git diff uses the same unified format but adds smart rename detection and color. delta (modern-tools track) makes diffs human-readable. For directory comparison, diff -rq dir1 dir2 + manual review beats most GUI tools.

A diff does not decide which side is correct

It reports difference, not truth. Normalize meaningless variation such as generated times, sort order, or locale only after checking that normalization does not erase a real change.

Use exit status as the automation contract

Typical diff returns 0 for equal, 1 for different, and another value for comparison error. Keep all three branches distinct in CI.

Code

Compare two files / dirs·bash
diff -u old.conf new.conf
diff -rq build1/ build2/        # which files differ?
diff -u config.yaml ~/.config/app/config.yaml > my-changes.patch

External links

Exercise

Make a copy of a file: cp ~/.zshrc /tmp/zshrc.old. Edit the copy. Then diff -u /tmp/zshrc.old ~/.zshrc | head -30 to see the unified diff. Save it as a patch: diff -u ... > /tmp/my.patch.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.