Comparing Changes with Diff

Chapter 6: Comparing Changes with Diff

While git status tells you which files have changed, git diff tells you exactly what changed inside those files.

Reading a Diff

A diff shows the differences between two versions of a file. Lines that have been added are marked with a + and are usually shown in green. Lines that have been removed are marked with a - and are usually shown in red.

--- a/hello.txt
+++ b/hello.txt
@@ -1,3 +1,3 @@
 Hello World
-This is a test.
+This is a Git test.
 Have a nice day!

The Three Faces of git diff

Git allows you to compare different stages of your workflow.

1. Working Directory vs. Staging Area

By default, git diff shows you the changes you have made that are not yet staged. Use this to review your work before adding it to the staging area.

git diff

2. Staging Area vs. Last Commit

To see what changes you have staged (using git add) but not yet committed, use the --staged or --cached flag:

git diff --staged

3. Comparing Commits

You can compare any two points in your project's history by providing their commit hashes:

git diff hash1 hash2

Comparing Branches

You can also compare the differences between two branches:

git diff main feature-branch

Useful Diff Flags

  • --stat: Show a summary of changes (which files, how many insertions/deletions).
  • -w: Ignore whitespace changes. This is very useful when you've just reformatted code but haven't changed the logic.
  • --word-diff: Instead of showing line changes, this highlights changed words within a line.

Using External Diff Tools

Many developers find it difficult to read diffs in the terminal. You can configure Git to use an external tool like VS Code, Beyond Compare, or Kaleidoscope:

git difftool

In the next chapter, we'll learn how to "time travel" and undo changes when we make mistakes.