Search code examples
gitdebugginggit-diff

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!!


Solution

  • 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