Git Diff: Understanding and Comparing Changes in Your Code
2025-03-03Introduction
Git diff is a helpful command that lets you see exactly what has changed in your project. Whether you're checking your current work, reviewing staged changes, or comparing different commits, git diff shows you the differences line by line.
What is Git Diff?
Git diff compares various states of your repository and highlights changes. It can show differences between:
- Your working directory and the last commit.
- Your staged changes and the last commit.
- Two different commits or branches.
How to Use Git Diff
Comparing Working Directory with Last Commit
To see changes in your working directory that haven't been staged yet, run:
git diff
Comparing Staged Changes
If you want to review changes that have been added to the staging area, use:
git diff --staged
Comparing Two Commits or Branches
You can compare any two commits or branches by specifying their commit hashes or names:
git diff commit1 commit2
For example, to see what differs between your current branch and main
, run:
git diff main
Additional Options
Git diff includes several useful options to tailor its output:
- --color: Highlights changes in color to make them easier to see.
- --word-diff: Shows changes word by word rather than line by line.
- -U<n>: Shows a specified number of context lines around changes (e.g.,
-U3
).
Best Practices
- Review your changes with
git diff
before staging to catch mistakes early. - Use diff options to adjust the output to your needs—this can help especially in large codebases.
- Combine
git diff
with other commands likegit log
for a comprehensive view of your project's evolution.
Conclusion
Git diff is a vital tool for understanding changes in your code. By mastering its various options and techniques, you can effectively review modifications, debug issues, and collaborate more efficiently. Keep practicing with git diff to make your development process smoother and more controlled.