Viewing Changes with 'git diff'
What You'll Learn
You'll learn how to use git diff to see exactly what has changed between different versions of your files in Git.
Understanding git diff
Think of git diff as a "before and after" comparison tool. Just as you might compare two drafts of an essay to see what you edited, git diff shows you line-by-line differences between versions of your code. This is crucial for reviewing your work before committing or understanding what changed since your last commit.
Basic git diff Commands
Comparing working directory to staged area:
git diff
This shows changes you've made but haven't yet staged with git add. It answers: "What did I modify that I haven't prepared to commit?"
Comparing staged changes to last commit:
git diff --staged
(or git diff --cached)
This reveals what will go into your next commit—the differences between what you've staged and the last committed version.
Comparing working directory to last commit:
git diff HEAD
This shows all changes since your last commit, whether staged or not.
Reading the Output
The output uses + for added lines and - for removed lines. Modified lines appear as a removal followed by an addition. The diff also shows context lines around changes to help you understand where modifications occurred.
Why This Matters
Before committing, git diff lets you verify exactly what you're about to save. It prevents accidental commits of debugging code, sensitive data, or unfinished work. It's your safety check before making changes permanent in the repository history.
Key Takeaway: Use git diff to compare your working directory changes against staged or committed versions, ensuring you always know exactly what modifications you're about to commit.