Finding Bugs with Git Bisect
What you'll learn: How to use Git's binary search tool to quickly pinpoint exactly which commit introduced a bug.
The Problem: Hunting for the Breaking Change
Imagine you discover a bug in your code today, but the code worked fine two weeks ago. Somewhere in those 100+ commits, something broke. You could check each commit one by one, but that's tedious and slow.
How Git Bisect Works
git bisect performs a binary search through your commit history. Think of it like the game "guess a number between 1 and 100"—instead of guessing randomly, you ask "is it higher or lower than 50?" Each answer eliminates half the possibilities.
Here's the process:
- Start bisect mode:
git bisect start - Mark the bad commit:
git bisect bad(usually HEAD, where the bug exists) - Mark a known good commit:
git bisect good <commit-hash>(from when it worked) - Test and mark: Git checks out a commit halfway between good and bad. You test it and tell Git
git bisect goodorgit bisect bad - Repeat: Git keeps narrowing down, halving the search space each time
- Found! Git identifies the exact commit that introduced the bug
- Exit:
git bisect resetto return to your original branch
Why This Matters
With 100 commits, checking each manually takes 100 tests. Binary search takes only about 7 tests (log₂(100) ≈ 6.6). That's a massive time-saver when debugging regressions.
Once you've found the guilty commit, you can read its message, see what changed, understand why it broke, and fix it properly.
Key Takeaway: Git bisect uses binary search to efficiently locate bug-introducing commits, dramatically reducing debugging time from linear to logarithmic complexity.