You’ve booted up the app you are developing, and the HEAD revision is borked. There are a ton of people committing, and you have no idea how to find the offending commit. Luckily if you are using Git, there is a command called bisect that will find the offending commit for you, pain free.

Bisect will let you mark a good commit and a bad one, and will checkout the middle commits until you find the offending revision. From there the resolving the bug is just a bit easier!

Step 1: Find a Good Commit

First, you need to find an old commit where the code isn’t broken. Maybe you have a good idea where to start, such as a large merge or something, or maybe you just checkout an arbitrary commit from last week, and go back from there. I do this by checking out the revision, confirming if things work, then copying the hash if they do.

git checkout 1234567

Step 2: Start Bisecting!

Get back to the head revision of your working branch (master, develop, etc.) and start the bisect.

git checkout develop
git bisect start

Now, mark the good and bad revisions. Since we know the head revision is broken, mark it as bad.

git bisect bad

Next, take the hash from above that we know works, and mark it as good.

git bisect good 12345676

After this is run, Git will tell you how many revisions between these commits, as well as the number of steps you’ll need to go through. For each step, git will check out the middle revision. You’ll build your code from that revision, and confirm whether the code is still broken or not.

In the below example, the first line tells you that there are 282 revisions to check. It also states bisect will take 8 steps to find the offending commit.

In the second line, Git tells you some info on the middle commit it has now checked out. The code is now running from this commit, so you can check in the browser and see if it’s broken.

Bisecting: 282 revisions left to test after this (roughly 8 steps)
[ec56789] This is a commit

If it’s broken, you’ll run git bisect bad. If not, git bisect good. Bisect will then check out the next middle revision (step 2 in the 8 steps). You’ll keep marking each until there are no revisions left.

Step 3: The Offending Commit

Once you mark the last commit, you’ll see a message like this:

3afdabb169fb2ab65a873e138570473a68958f43 is the first bad commit
commit 3afdabb169fb2ab65a873e138570473a68958f43
Author: Rob Stinogle <stinogle@gmail.com>
Date: Wed Nov 25 10:30:53 2014 -0700
This is a commit message for a broken commit...

Now you know the commit that broke the app. WIN.

To get your branch out of the bisecting state, run the below command. It will check your branch out to the HEAD revision.

git bisect reset

You’ve got the offending commit, now go and fix it!