Git Diff

1 min

Table of contents

  1. What Is Diff?
  2. See the Differences
  3. Types of Diff
  4. Quick Reading
  5. Practical Commands

1. What Is Diff?

Git diff = See EXACTLY what changed in your files.

Why is it crucial?

  • Before committing: check your modifications
  • Debugging: understand what broke
  • Review: see colleagues' work

In short: diff = your glasses for seeing changes!

Back to table of contents

2. See the Differences

bash
mkdir demo-diff && cd demo-diff
git init

echo "print('Version 1')" > app.py
git add . && git commit -m "Initial version"

# Modify the file
echo "print('Version 2 - Updated!')" > app.py

# See the changes
git diff                    # Comparison working directory vs last commits

# Add to staging
git add app.py

# See staged difference vs last commits
git diff --staged

# See difference between 2 commits
git log --oneline          # Retrieve the hashes
git diff <hash1> <hash2>

Back to table of contents

3. Types of Diff

CommandCompares
git diffWorking directory vs last commit
git diff --stagedStaging area vs last commit
git diff HEADWorking directory + staging vs last commit
git diff <commit1> <commit2>Between 2 specific commits
git diff <branch1> <branch2>Between 2 branches

Back to table of contents

4. Quick Reading

Typical format:

diff --git a/app.py b/app.py
index abc123..def456 100644
--- a/app.py          # Old file
+++ b/app.py          # New file
@@ -1 +1 @@           # Position of the changes
-print('Version 1')   # Deleted line (red)
+print('Version 2')   # Added line (green)

Express reading:

  • --- and +++ = compared files
  • - = deleted (red in the terminal)
  • + = added (green in the terminal)

Back to table of contents

5. Practical Commands

CommandUse
git diff --name-onlyJust the names of modified files
git diff --statChange statistics
git diff --word-diffDifferences at the word level
git diff HEAD~1 HEADLast commit vs the one before

Diff = your change detector. Use it ALL THE TIME!

Back to table of contents