Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using git to compare one file from two commits

I have a file that has broken somewhere down the line, and I have found the last point in which it was still fixed.

I would like to know how, using git, I can compare one file from two commits, or indeed if that is the best way to play this!!

like image 722
Mild Fuzz Avatar asked Apr 05 '11 10:04

Mild Fuzz


People also ask

How do I compare in git?

In case you are using the Tower Git GUI, comparing branches is very easy. You can simply select the branches in the sidebar, right-click, and select the "Compare..." option from the contextual menu. Tower will then start a comparison and show the differing changes in your favorite diff tool.

Which command checks difference between the previous two commits?

"git diff" always show the difference between two commits (or commit and working directory, etc.).

What does git diff do?

Comparing changes with git diff Diffing is a function that takes two input data sets and outputs the changes between them. git diff is a multi-use Git command that when executed runs a diff function on Git data sources. These data sources can be commits, branches, files and more.


1 Answers

To directly answer your question, suppose you want to compare the file src/toaster.c between your current master and the old commit f4l4f3l, you can just do:

git diff master f4l4f3l -- src/toaster.c

As an alternative, you can just look through all the changes to that file with:

git log -p -- src/toaster.c

More generally, however, if you're trying to find the commit where a particular bug was introduced, git has a marvellous tool for this, called git bisect. If you tell this tool a working and non-working commit, it will give you a series of commits to test in between those, using a binary search strategy.

You would start bisecting with the command:

git bisect start

Then if your current commit has the bug, you just do:

git bisect bad

Next, you need to find an older commit that definitely didn't have the bug. This might have a particular tag, or perhaps you'll just pick a commit that was some months ago. Suppose that one is called a12b3d, then you would do:

git checkout a12b3d
git bisect good

At that point, git will work out the next commit you'll need to test, and do git checkout to move you to that commit. (These checkouts will all be with "detached HEAD", so your original branch pointer is unchanged.) You then test that commit, and run git bisect good or git bisect bad depending on whether it has the bug or not. This binary search between the revisions will quickly narrow down to the first bad commit, and report which one it is. Then to go back to what you were doing, you can do:

git bisect reset
like image 73
Mark Longair Avatar answered Sep 28 '22 07:09

Mark Longair