Binary-searching for a bug in git
- roymattars
- Jul 25, 2020
- 2 min read
Updated: Aug 20, 2020
Have you ever worked on a project using git and saved the changes in your code in several commits, only to find out later on that you’ve introduced a bug somewhere along the road? More often than not, you could even not know where in the code the bug is.
We’ve all been there.
I have, yesterday. Of course, this would have been avoided had I run and tested the code before each and every commit. But when you're working with embedded systems, that would require the cumbersome process of burning the code onto the hardware and performing manual tests on it. Add to that the aspiration towards multiple short commits… You get the point.
Fortunately, git has a feature exactly for that, which you might not have known about.

It is git bisect.
It's like a little helper. The way it works is that you provide it with two points of reference – one commit with the mysterious bug and an earlier one which is okay. Just like in binary search, your helper will offer you a commit from the middle of the range of history. You will be able to run your program and report if it’s buggy or not. Using the process of elimination, after a few bisect runs the problematic commit will be pointed out.
Here is how you would use it.
Use:
git bisect start
to start up this feature.
Then:
git bisect bad
to tell it the current version is buggy, and:
git bisect good <COMMIT_HASH>
to tell it about a version which is not.
It will now start working its magic. After picking a commit and checking it out, it will display something along the lines of:
Bisecting: 45 revisions left to test after this (roughly 6 steps)
Repeat the process, all the while commanding 'git bisect bad' or 'git bisect good'.
Eventually there will be no commits left to inspect, and your helper will output the first bad commit. When the process is done, run this command to clean up and return to the HEAD:
git bisect reset

What can you then do with the bad commit? You can go back and fix it, using git features such as git rebase --interactive and git commit --amend.
I encourage you to make use of this helper the next time you run into this kind of situation. Hopefully, it will make tracking down your bug a breeze as it did for me. :)
Comments