Git’s diff
command is invaluable for understanding changes in your project. It allows you to compare different versions of your files, pinpoint modifications, and review changes before committing them. This tutorial will cover the core uses of git diff
, focusing on clarity and practical application.
Table of Contents
- Comparing Your Working Copy to the Repository
- Comparing the Staging Area to the Repository
- Using External Diff Tools
- Advanced
git diff
Options
Comparing Your Working Copy to the Repository
Your working copy represents the project files on your local machine. The repository stores the version history managed by Git. git diff
(without arguments) shows unstaged changes in your working copy:
git diff
The output displays additions (+
), deletions (-
), and modifications. For example:
--- a/my_file.txt
+++ b/my_file.txt
@@ -1,3 +1,4 @@
This is line 1
This is line 2
+This is a new line
This is line 3
This indicates a new line added to my_file.txt
. --- a/
and +++ b/
represent the old and new file versions. To compare a specific file:
git diff my_file.txt
Comparing the Staging Area to the Repository
The staging area holds changes you’ve prepared for the next commit. git diff --staged
(or git diff --cached
) reveals the difference between staged changes and the last commit:
git diff --staged
This is crucial for reviewing changes before committing. You can specify filenames to limit the comparison.
Using External Diff Tools
Git’s default text-based diff can be challenging for complex changes. External diff tools offer visual comparisons, syntax highlighting, and other helpful features. Configure an external tool (like Meld, KDiff3, Beyond Compare) using git config
:
git config --global diff.external meld
Replace meld
with your tool’s command. Consult your tool’s documentation for the correct command and any necessary system-specific adjustments.
Advanced git diff
Options
git diff
offers many more options. For instance:
git diff --check
: Detects whitespace errors.git diff --summary
: Provides a concise summary of changes.git diff ..
: Compares two commits.git diff --word-diff
: Highlights changes word-by-word.
Experiment with these options to tailor git diff
to your workflow. Mastering git diff
is essential for efficient Git usage.