Git Diff Tutorial
Overview
The git diff
command is used to show changes between commits, commit and working tree, etc. It is a versatile command that can compare branches, commits, and changes in the working directory. This document will cover various usages of git diff
with examples.
Table of Contents
- Basic Syntax
- Comparing Working Directory and Index
- Comparing Staged Changes
- Comparing Working Directory and Last Commit
- Comparing Between Commits
- Comparing Branches
- Diffing Specific Files
- Diffing with Different Output Formats
- Ignoring Whitespace Changes
- Useful Tips
Basic Syntax
The basic syntax of git diff
is:
Comparing Working Directory and Index
To see the changes that you have made but not yet staged, use:
Example
This will show the changes in the working directory that are not staged for the next commit.
Comparing Staged Changes
To see the changes that are staged for the next commit, use:
Example
This will show the changes that have been staged but not yet committed.
Comparing Working Directory and Last Commit
To see the changes between the working directory and the last commit, use:
Example
This will show the changes in the working directory compared to the latest commit.
Comparing Between Commits
To see the changes between two commits, use:
Example
This will show the changes between commit1
and commit2
.
Comparing Branches
To see the changes between two branches, use:
Example
This will show the differences between the main
branch and the feature-branch
.
Diffing Specific Files
To see the changes for a specific file, use:
Example
This will show the changes in README.md
.
Diffing with Different Output Formats
git diff
supports different output formats. The most common are:
- Patch format (default): Shows the changes as a patch.
- Name-only format: Shows the names of the changed files.
- Name-status format: Shows the names and statuses (added, modified, deleted) of the changed files.
Examples
Patch Format
Name-Only Format
Name-Status Format
Ignoring Whitespace Changes
To ignore whitespace changes, use:
Example
This will ignore whitespace changes in the diff output.
Useful Tips
-
Color Diff Output: Use
--color
to force color diff output: -
Word Diff: Use
--word-diff
to show changes word by word: -
Context Lines: Use
-U<n>
to show<n>
lines of context around changes:
Summary
The git diff
command is an essential tool for understanding changes in your Git repository. By using the various options and formats available, you can tailor the output to your needs and gain better insight into the differences between commits, branches, and your working directory.