Git Diff: Comparing Changes in Your Code
git diff
shows the differences between files or commits. It's useful to see what changes have been made in your working directory, staging area, or between commits.
1. Viewing Differences in Your Working Directory
1.1 Check Unstaged Changes
To see the differences between your working directory and the last commit (for unstaged changes):
🔹 This shows the changes you made but have not staged yet.
1.2 Check Staged Changes
To see what is staged but not committed yet:
🔹 This shows the differences between the staged changes and the last commit.
2. Comparing Two Commits
You can compare any two commits by specifying their commit hashes.
To compare changes between two commits:
🔹 This shows the differences between the two specified commits.
3. Comparing Branches
You can also compare changes between branches.
To compare the differences between branch1
and branch2
:
🔹 This shows the differences between the two branches.
4. Viewing Differences in Specific Files
To compare a specific file or directory between your working directory and the last commit:
🔹 This shows only the differences for that specific file.
To compare a specific file between commits or branches:
5. Output Formatting Options
You can customize the output of git diff
using different options:
5.1 Summary of Changes
To see only a summary of the changes:
🔹 This shows the number of files changed, lines added, and removed.
5.2 Word-wise Diff
To see a word-by-word diff (useful for small changes):
6. Applying Changes from a Diff
If you want to apply a diff (patch) from a file or output:
🔹 This applies the changes from a patch file (you can save the output of git diff
to a patch file).
7. Conclusion
Action | Command |
---|---|
View unstaged changes | git diff |
View staged changes | git diff --staged |
Compare two commits | git diff <commit-hash1> <commit-hash2> |
Compare two branches | git diff branch1..branch2 |
Compare specific file | git diff path/to/file |
Show a summary of changes | git diff --stat |
Word-by-word diff | git diff --word-diff |
Apply changes from diff | git apply <patch-file> |
🔹 git diff
is great for reviewing changes before committing! Need help with a specific use case? 🚀