How to Find Bugs Using Git Bisect: Step-by-Step Guide
Use
git bisect to find the commit that introduced a bug by marking a known good commit and a bad commit, then testing commits in between. Git will guide you through a binary search to isolate the exact commit causing the issue.Syntax
The basic git bisect workflow involves starting the bisect session, marking commits as good or bad, and letting Git narrow down the culprit commit.
git bisect start: Begin the bisect process.git bisect bad: Mark the current commit as bad (where the bug exists).git bisect good <commit>: Mark a known good commit (where the bug did not exist).git bisect reset: End the bisect session and return to the original branch.
bash
git bisect start # Mark current commit as bad git bisect bad # Mark known good commit git bisect good <commit> # After testing each commit, mark it good or bad # Repeat until Git finds the first bad commit # End bisect session git bisect reset
Example
This example shows how to find the commit that introduced a bug using git bisect. Assume the current commit is bad and abc1234 is a known good commit.
bash
git bisect start # Mark current commit as bad git bisect bad # Mark known good commit git bisect good abc1234 # Git checks out a commit in the middle # Test the code manually or run tests # If bug exists, mark bad git bisect bad # If bug does not exist, mark good git bisect good # Repeat until Git finds the first bad commit # When done, reset to original branch git bisect reset
Output
Bisecting: 3 revisions left to test after this (roughly 2 steps)
[def5678] Fix typo in README
Bisecting: 1 revision left to test after this (roughly 1 step)
[789abcd] Add new feature
abc1234 is the first bad commit
Common Pitfalls
- Not marking commits correctly: Always mark the current commit as
goodorbadafter testing. - Using wrong good commit: The good commit must be before the bug appeared.
- Not resetting bisect: Always run
git bisect resetto return to your original branch. - Automate tests: Manual testing slows down bisect; use scripts if possible.
bash
git bisect start # Wrong: marking good commit as bad git bisect bad # Correct: git bisect bad git bisect good abc1234
Quick Reference
| Command | Description |
|---|---|
| git bisect start | Start bisect session |
| git bisect bad | Mark current commit as bad |
| git bisect good | Mark known good commit |
| git bisect reset | End bisect and return to original branch |
Key Takeaways
Start bisect with a known bad and good commit to isolate the bug.
Mark each tested commit as good or bad to guide Git's search.
Always reset bisect to return to your original branch.
Automate testing during bisect to speed up bug finding.
Choose the good commit carefully to avoid confusion.