Git Bisect: Find the Commit That Introduced a Bug
Use git bisect to perform a binary search through your commit history and pinpoint exactly which commit introduced a bug or regression.
git bisect start && git bisect bad && git bisect good <commit>Detailed Explanation
What Does git bisect Do?
git bisect performs a binary search through your commit history to find the exact commit that introduced a bug. Instead of checking every commit one by one, bisect halves the search space with each step, making it incredibly efficient even across thousands of commits.
How It Works
- You tell Git which commit is "bad" (has the bug) and which is "good" (does not).
- Git checks out a commit halfway between the two.
- You test that commit and mark it as "good" or "bad".
- Git narrows the range and checks out another midpoint.
- This repeats until the offending commit is found.
Step-by-Step Example
# Start bisecting
git bisect start
# Mark the current commit as bad
git bisect bad
# Mark a known good commit (e.g., from last week)
git bisect good v2.1.0
# Git checks out a midpoint. Test it, then:
git bisect good # if the bug is NOT present
# or
git bisect bad # if the bug IS present
# Repeat until Git identifies the culprit
# Git will print: "<hash> is the first bad commit"
# End the bisect session
git bisect reset
Automating Bisect
If you have a test script that exits with 0 for good and non-zero for bad:
git bisect start
git bisect bad HEAD
git bisect good v2.1.0
git bisect run ./test-script.sh
Git will automatically run the script at each midpoint and find the offending commit without manual intervention.
Tips
Bisect works best when commits are small and atomic. If a single commit introduces thousands of changes, the result is less actionable. Pair bisect with git blame and git log to understand the context once you find the culprit.
Use Case
A performance regression appeared somewhere in the last 200 commits. The team uses git bisect with an automated benchmark script to locate the exact commit responsible.