Git & GitHub Course
Git & GitHub
/
Intermediate

git diff

Definition

Shows changes between commits, commit and working tree, etc. It highlights exactly what lines of code you have altered since your last save.

Explain Like I'm New

Before you commit, you should check what you actually did. `git diff` shows you the exact lines of code you typed or deleted in your Working Directory since your last commit.

Real World Example

You are about to type `git commit`, but you pause and think: 'Wait, did I accidentally leave a console.log() in there?' You run `git diff` to double check your work.

Common Use Cases

  • •Reviewing your own work before staging
  • •Comparing branches

Crucial Command Flags

Flag / OptionDescription
--staged / --cachedShow changes that are staged but not yet committed.
HEADShow all changes (staged and unstaged) since the last commit.
--name-onlyShow only the names of changed files, not the actual code changes.

Terminal Output

bash / terminal
# 1. You edit index.html. # See what you changed (Working Directory vs Staging Area) $ git diff # 2. You run 'git add index.html'. # Now 'git diff' outputs nothing! It's staged. # 3. See what is staged (Staging Area vs Last Commit) $ git diff --staged # Compare two different branches to see how they differ $ git diff main feature-branch

Interview Questions

basic

  • Does `git diff` show files that have already been `added` to the staging area?

intermediate

  • How do you see the diff of files that ARE in the staging area?

Flash Cards

Question

Show staged files?

Click to reveal answer
Answer

No! By default, `git diff` ONLY compares the Working Directory to the Staging Area. If a file is staged, it disappears from the default `git diff` output.

Question

Diff staged files?

Click to reveal answer
Answer

You must use the command `git diff --staged` (or `--cached`). This compares the Staging Area to the last Commit.