In this lesson, you will learn how to pinpoint the exact line-by-line changes made to a specific file by comparing two different snapshots in your project history.
So far, you’ve learned how to view your commit history using git log. While logs tell you who changed a file and when, sometimes you need to see exactly what changed between two points in time. You can do this by using the git diff command combined with commit hashes.
Using git diff with Commit Hashes
To compare a specific file between two commits, you provide the command with the two unique commit identifiers (hashes) followed by the path to the file. The syntax looks like this:
git diff <commit-hash-1> <commit-hash-2> -- <file-path>
Imagine you are looking at a file named README.md. You want to see how it evolved between your third commit (a1b2c3d) and your latest commit (e4f5g6h). You would run:
git diff a1b2c3d e4f5g6h -- README.md
Understanding the Output
When you run this command, Git displays a "diff" output that highlights the differences:
- Lines starting with
-: These represent content that existed in the first commit but was removed or modified by the time the second commit was made. - Lines starting with
+: These represent new content that was added in the second commit. - Context lines: Git will also show surrounding unchanged lines (starting with a space) to help you locate exactly where in the file the change occurred.
This tool is invaluable for debugging. If a feature was working in an earlier version of your project but broke later, you can use git diff to isolate the specific lines of code that were modified between those two points. By focusing only on the file that interests you, you avoid the noise of unrelated changes, allowing you to quickly spot the cause of a regression or a logic error.
Key Takeaway: You can use git diff <hash1> <hash2> -- <filename> to surgically examine the exact line-by-line evolution of any file across your project's history.