1. Home
  2. Blog
  3. DevOps

DevOps

Git Diff Explained: Staged Changes, Branches and Commits

git diff shows exactly what changed between your working files, the staging area, commits and branches. Learn how to read its output line by line, which form to use when, the two-dot vs three-dot difference, and the flags that make big diffs readable, all run in a real repository.

9 min read
Git diff explained: staged changes, branches and commits

Key takeaways

  • git diff alone shows only unstaged changes. After git add, they vanish from it.
  • git diff --staged (same as --cached) shows what your next commit will contain.
  • main..feature compares branch tips; main...feature shows only what the feature branch changed since it split off. That is usually what you want before a merge.
  • git diff ignores untracked files and returns exit code 1 with --quiet when changes exist, which is handy in scripts.

Before you commit, before you merge and whenever a build suddenly breaks, the question is the same: what exactly changed? git diff answers it, line by line. It is one of the most used Git commands, yet many developers know only its default form and are confused when it shows nothing after git add, or when a branch comparison lists changes they never made.

We ran every command in this guide in a throwaway repository with Git 2.56, and the output is copied from those runs. New to Git? Start with our Git tutorial for beginners.

What is git diff?

The command compares two snapshots of your project and prints the differences in a standard “unified diff” format. Depending on its arguments, the two sides can be your working directory, the staging area (also called the index), any commit, or any branch. It never changes anything; it only reports.

The three areas git diff compares

Command Left side Right side
git diff Staging area Working directory
git diff --staged Last commit (HEAD) Staging area
git diff HEAD Last commit (HEAD) Working directory
git diff A B Commit A Commit B

Keep this table in mind and the “where did my changes go?” moments disappear.

Our test repository

We created a tiny shop app with one commit, then changed the total function to add tax. To keep personal details out of the output we used a throwaway identity, Demo with demo@example.com, and a fixed commit date.

git init -b main
# app.py: def total(items): return sum(items)
git add . && git commit -m "Initial shop app"
# edit app.py to add a tax parameter

Reading git diff output

diff --git a/app.py b/app.py
index 9011f18..5567491 100644
--- a/app.py
+++ b/app.py
@@ -1,4 +1,4 @@
-def total(items):
-    return sum(items)
+def total(items, tax=0.18):
+    return round(sum(items) * (1 + tax), 2)
 
 TAX = 0.18
  • diff –git a/app.py b/app.py: the file being compared. a/ is the old side, b/ the new side.
  • index 9011f18..5567491 100644: short IDs of the old and new file contents, then the file mode (a normal, non-executable file).
  • — and +++: which lines belong to the old and new version.
  • @@ -1,4 +1,4 @@: the hunk header. The old file’s section starts at line 1 and spans 4 lines; so does the new one.
  • Lines starting with – were removed, + were added, and a leading space means unchanged context.

A changed line is shown as a removal plus an addition. Git shows three lines of context around each change by default; -U1 or -U10 changes that.

Unstaged changes: git diff

The output above came from plain git diff right after editing the file. Now watch what happens after staging:

git add app.py
git diff
# (no output)

Nothing! The change did not disappear; it moved into the staging area, and plain git diff only compares the staging area with your working files. This is the single most common confusion with the command.

Staged changes: git diff –staged

git diff --staged --stat
 app.py | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

--staged shows exactly what will go into the next commit. Making it a habit before every git commit catches debug prints, stray files and secrets before they enter history. --cached is an older name for the same option. A Git pre-commit hook can automate checks on the same staged content.

We then edited README.md without staging it, so the repository held one staged change and one unstaged change:

git diff HEAD --stat
 README.md | 1 +
 app.py    | 4 ++--
 2 files changed, 3 insertions(+), 2 deletions(-)

git diff HEAD combines both: every difference between the last commit and your working files, staged or not. Use it when you want the full picture of uncommitted work, for example before deciding whether to stash it.

Comparing commits

git diff HEAD~1 HEAD --stat
 README.md | 1 +
 1 file changed, 1 insertion(+)

Pass any two commit references: hashes, tags, HEAD~2, or branch names. The order matters: the first is the old side, so swapping them flips every + and -. To see one commit’s changes together with its message, git show <commit> is shorter. Hunting for the commit that broke something? git bisect automates that search.

Comparing branches: two dots vs three dots

We created a feature branch that added a discount function, then went back to main and committed a license line to README.md. The branches had diverged:

git diff --stat main..feature
 README.md | 1 -
 app.py    | 3 +++
 2 files changed, 3 insertions(+), 1 deletion(-)

git diff --stat main...feature
 app.py | 3 +++
 1 file changed, 3 insertions(+)

The two-dot form (the same as git diff main feature) compares the two branch tips directly. Because main gained a README line that feature lacks, the feature branch appears to delete it, which is misleading. The three-dot form compares feature with the point where it branched off main, so it shows only the work done on the feature branch. That matches what a pull request shows, and it is the right command for reviewing a branch before a merge. Our merge vs rebase guide explains how those diverged commits get combined.

Tip: for reviews, use git diff main...feature. If a branch diff shows changes you never made, you probably used two dots on diverged branches.

Just the file names, or a summary

git diff HEAD --name-only
README.md
app.py

git diff HEAD --name-status
M	README.md
M	app.py

--name-only lists changed paths, perfect for feeding into a linter or test runner. --name-status adds a letter: M modified, A added, D deleted, R renamed. --stat, used throughout this guide, shows a per-file bar chart of insertions and deletions.

Word-level diffs

git diff --word-diff HEAD~2 HEAD~1 -- app.py
    return [-sum(items)-]{+round(sum(items) * (1 + tax), 2)+}

For long lines, prose and Markdown, a line-based diff hides what changed inside the line. --word-diff marks removed words with [-...-] and added words with {+...+}. In a terminal, --color-words shows the same thing with colours only. The -- before the path separates options and revisions from file names.

Ignoring whitespace changes

We re-indented one line in app.py, changing only its leading spaces:

git diff --stat
 app.py | 2 +-
git diff -w --stat
# (no output)

-w (ignore all whitespace) hid the change completely. It is ideal when reviewing code after a formatter run or an indentation fix. Be careful with languages where indentation matters, such as Python and YAML: a whitespace-only change can still change behaviour.

Using git diff in scripts

git diff --quiet; echo $?   # 0 when clean
echo x >> README.md
git diff --quiet; echo $?   # 1 when there are changes

--quiet prints nothing and uses the exit code: 0 for no differences, 1 for differences. CI scripts use it to fail a build when a code generator or formatter leaves uncommitted changes, for example git diff --exit-code after running a formatter.

Why git diff ignores new files

echo "new" > notes.txt
git diff --stat
# (no output: untracked files are not shown)

git add -N notes.txt
git diff --stat
 notes.txt | 1 +

Untracked files are not part of the staging area, so there is nothing to compare them with. git status lists them. To include a new file in git diff without staging its content, mark it with git add -N (intent to add). Files that should never be tracked belong in .gitignore.

Git diff cheat sheet

You want to see Command
Unstaged changes git diff
What the next commit will contain git diff --staged
All uncommitted changes git diff HEAD
One file only git diff -- path/to/file
Work done on a branch git diff main...feature
Changes between two commits git diff A B
Changed file names git diff --name-only
Summary counts git diff --stat
Ignore whitespace git diff -w
Changes inside long lines git diff --word-diff

For the wider command set, see our Git commands cheat sheet.

Final thoughts

The command becomes simple once you know which two snapshots it compares: plain git diff for unstaged work, --staged for the next commit, HEAD for everything, and three dots for a branch review. Learn to read the hunk headers and plus and minus lines, reach for --stat, --word-diff and -w when output gets noisy, and you will catch most mistakes before they become commits.

Frequently asked questions

Why does git diff show nothing after git add?

Plain git diff compares the staging area with your working files. After git add, the change is in the staging area, so use git diff with the staged option to see it.

What is the difference between staged and cached in git diff?

There is no difference. The staged and cached options are two names for the same thing: they compare the last commit with the staging area.

How do I compare two branches in Git?

Use the three-dot form, with main and feature separated by three dots, to see only the changes made on the feature branch since it split from main. Use two dots, or a space, to compare the two branch tips directly.

How do I see only the names of changed files?

Add the name-only option to any git diff command. The name-status option also shows whether each file was modified, added, deleted or renamed.

Does git diff show new untracked files?

No. Untracked files are not compared. Use git status to list them, or mark a file with git add and the intent-to-add flag N so that git diff includes it.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Softmax Function Explained: Formula, Python Code and Stable Version

The softmax function explained: formula, worked example, NumPy code, the stable version that avoids NaN, temperature, cross-entropy and softmax vs…

Read article →
Software Development

CORS Explained: Preflight Requests, Headers and How to Fix CORS Errors

CORS explained: origins, simple and preflight requests, the response headers your server must send, credentials, and how to fix common…

Read article →
DevOps

Git Diff Explained: Staged Changes, Branches and Commits

Git diff explained: read the output, compare unstaged and staged changes, commits and branches, two dots vs three dots, and…

Read article →
Test Automation

Pytest Xdist: Run Tests in Parallel and Cut Test Time

Run pytest tests in parallel with pytest-xdist: install, the -n option, distribution modes, real timings and how to fix shared-state…

Read article →
Software Testing

Verification vs Validation in Software Testing: Example and Table

Verification vs validation in software testing explained with a comparison table and a tested coupon example where every spec test…

Read article →
Databases & SQL

SQL CAST Explained: Convert Data Types With Tested Examples

SQL CAST explained with tested examples: text to number, truncation, integer division, numbers stored as text, dates, bad input and…

Read article →
Databases & SQL

SQL DISTINCT: How to Remove Duplicate Rows (and Its Traps)

SQL DISTINCT explained with tested queries: one and many columns, NULLs, COUNT DISTINCT, DISTINCT vs GROUP BY, the SUM DISTINCT…

Read article →
Software Development

JavaScript Reduce Explained: 12 Practical Examples

JavaScript reduce explained step by step with 12 practical examples: sums, tallies, grouping, Maps, pipelines, sequential promises and the empty…

Read article →
Software Development

Python Random Module: randint, choice, seed and More

The Python random module explained: randint, randrange, choice, choices, sample, shuffle, seed, weights and when to use secrets instead, with…

Read article →
Software Development

Python Slicing Explained: Start, Stop and Step With Examples

Python slicing explained with start, stop and step, negative indexes, reversing, copying and slice assignment, with tested examples and a…

Read article →
Artificial Intelligence

Levenshtein Distance: Formula, Worked Table and Python Code

Levenshtein distance explained: the edit operations, the dynamic programming table for kitten and sitting, Python code with two-row memory, normalised…

Read article →
Software Development

URL Encoding Explained: Spaces, Plus Signs and UTF-8

URL encoding explained with tested Python and JavaScript code: percent encoding, reserved characters, %20 vs plus, UTF-8 bytes, encodeURI vs…

Read article →
DevOps

Gitignore: Patterns, Negation and Fixing Tracked Files

A tested gitignore guide: pattern rules, leading and trailing slashes, negation with !, the ignored parent folder trap, git check-ignore…

Read article →
Software Testing

Acceptance Criteria: Given When Then Examples and Checklist

How to write acceptance criteria testers can run: rule-based and Given When Then formats, a worked discount code example turned…

Read article →
Software Testing

State Transition Testing: Diagram, Table and Example

State transition testing explained with a login lockout example: states, events, the diagram, the state table, valid and invalid transitions,…

Read article →
Databases & SQL

Second Highest Salary in SQL: 5 Tested Ways and the Tie Trap

Find the second highest salary in SQL five ways: MAX subquery, LIMIT OFFSET, DENSE_RANK, a correlated subquery and per department,…

Read article →
Databases & SQL

SQL ROW_NUMBER: Top N per Group, Dedupe and Pagination

SQL ROW_NUMBER explained with tested queries: PARTITION BY, top N per group, deleting duplicates, pagination, the tie trap and how…

Read article →
Software Development

JavaScript Set: Union, Intersection and Removing Duplicates

JavaScript Set explained with tested examples: add, has, delete, deduplicating arrays, the new union and intersection methods, equality rules and…

Read article →
Test Automation

Python Unittest: Assert Methods, setUp and Mocks With Examples

A practical Python unittest tutorial: TestCase, assert methods, setUp and tearDown, subTest, skips, expected failures and mock, with a test…

Read article →
Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Databases & SQL

SQL Temporary Table: Create, Use and Drop It

SQL temporary tables store interim results for one session. Learn syntax for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, session…

Read article →
Databases & SQL

SQL CROSS JOIN: Every Combination + Examples

SQL CROSS JOIN returns every combination of rows from two tables. See the row math, product variants, calendar grids that…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →