BudiBadu Logo
Samplebadu

Git by Example: Diff View

2.43.0

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-login

Explanation

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 diff for unstaged changes
  • git diff --staged for staged changes
  • Uses unified diff format (+/-)

Code Breakdown

2
Displays changes in your working directory that have not been added to the staging area yet.
13
Displays changes that are staged and ready to be committed. Always check this before running 'git commit'.
19
Compares the tip of the 'main' branch with the 'feature-login' branch, showing all the differences between them.