Git by Example: Diff View
Learn how to inspect changes in your repository. This example covers comparing working directory, staging area, commits, and branches.
Code
# 1. Show unstaged changes (Working Directory vs Index)
git diff
# Output:
# diff --git a/app.js b/app.js
# index 1a2b3c..4d5e6f 100644
# --- a/app.js
# +++ b/app.js
# @@ -1,4 +1,5 @@
# const express = require('express');
# +const cors = require('cors');
# 2. Show staged changes (Index vs HEAD)
git diff --staged
# 3. Show all changes (Working Directory + Index vs HEAD)
git diff HEAD
# 4. Compare two branches
git diff main..feature-loginExplanation
The git diff command is one of the most frequently used tools in Git. It allows you to see exactly what has changed in your files line-by-line. By default, running git diff compares your working directory with the staging area (index). This shows you the modifications you have made but haven't yet staged for a commit.
To see what you have already staged and are about to commit, you use git diff --staged (or --cached). This compares the staging area with the last commit (HEAD). It is a best practice to run this before every commit to verify that you are including exactly what you intend to.
The output uses the "unified diff" format. Lines starting with a minus sign (-) in red show removed content, while lines starting with a plus sign (+) in green show added content. The header information tells you which files are being compared and provides context for where the changes occurred in the file.
- Shows line-by-line changes
git difffor unstaged changesgit diff --stagedfor staged changes- Uses unified diff format (+/-)

