Rezha Julio

The Hard Coded Chemist

Debug Bad Commit with Binary Search


Let’s say you just pushed out a release of your code to a production environment, you’re getting bug reports about something that wasn’t happening in your development environment, and you can’t imagine why the code is doing that. You go back to your code, and it turns out you can reproduce the issue, but you can’t figure out what is going wrong.

The git bisect tool helps to identify the commit that introduced a bug.

To start, you need to tell git when the code last ran without problems. Assuming you are currently in a place where the code fails:

$ git bisect start
$ git bisect bad # current commit has a bug
# checkout to a known good commit
$ git bisect good v2.1 # v2.1 passes the test

git will then check out the commit that is halfway between the good and bad commits. You test the code and if there was no problem:

$ git bisect good
# test halfway between middle and bad commit

If there was a problem:

$ git bisect bad
# test halfway between middle and good commit

You continue doing this until git identifies the first bad commit.

When you finish you need to reset to the original state to reset your HEAD to where you were before you started, or you’ll end up in a weird state:

$ git bisect reset