Blog Bisect a regression with git in five minutes
Bisect a regression with git in five minutes
TL;DR git bisect binary-searches your history to find the commit that introduced a bug. Mark a known-good and known-bad commit, then git checks out the midpoint and asks you to test. A few rounds pinpoint the exact commit, even across hundreds of them.
A bug that was not there last week is somewhere in the last hundred commits, and reading them one by one is misery. git bisect finds the exact commit that introduced it with a binary search, turning a hopeless hunt into a handful of quick tests.
How it works
You give bisect two anchors: a commit where the bug does not exist (good) and one where it does (bad). Git checks out the commit halfway between them and asks you to test. Based on your answer, it discards half the range and checks out the new midpoint. Each round halves what is left, so even a thousand commits take about ten tests.
Run a bisect
Start it, and mark your two anchors:
git bisect start
git bisect bad # current commit is broken
git bisect good v1.4.0 # this older commit worked
Git checks out a commit in the middle. Test it, then tell git what you found:
git bisect good # the bug is not here
# or
git bisect bad # the bug is here
Repeat. After a few rounds, git prints the first bad commit, the exact change that introduced the bug, with its diff.
When you are done, return to where you were:
git bisect reset
Automate it
If you can write a command that passes when the code is good and fails when it is broken, git will drive the whole search:
git bisect start HEAD v1.4.0
git bisect run npm test
Git tests each midpoint with your script and reports the culprit, no manual checking at all.
Why it beats guessing
Without bisect, finding a regression means reading diffs and forming theories, which is slow and often wrong. Bisect replaces intuition with a mechanical search that cannot miss: it will land on the exact commit every time, in a number of steps that barely grows as history does. Next time something "used to work," do not scroll the log. Bisect it, and let the binary search do the hunting.
FAQ
What does git bisect do?
It performs a binary search over your commit history to find the one that introduced a bug. You tell it a commit where things worked and one where they are broken, and it repeatedly checks out the midpoint for you to test, narrowing down to the exact culprit.
How many steps does bisect take?
Because it halves the range each time, it is logarithmic: around ten tests to search a thousand commits. A range that would take forever to check one by one collapses to a handful of steps.
Can I automate the testing?
Yes. git bisect run lets you supply a script that returns success or failure, and git drives the whole search automatically, testing each midpoint without you. Ideal when the check can be scripted.