Find the Commit That Broke Things with git bisect
"It worked last week." Somewhere among 200 commits, something broke. git bisect finds the culprit with a binary search: about 8 checks for 200 commits.
Manual bisect
git bisect start
git bisect bad # the current commit is broken
git bisect good v2.3.0 # this release was fine
# Git checks out a commit halfway between. Test it, then tell Git:
git bisect good # or: git bisect bad
# ...repeat until Git prints:
# 7c1f2e9 is the first bad commit
git bisect reset # return to where you started
If a commit can't be tested (it doesn't build for unrelated reasons), run git bisect skip.
Automated bisect
If a script can tell good from bad, let Git do all the work. The script exits 0 for good and 1 for bad (125 means skip):
git bisect start HEAD v2.3.0
git bisect run npm test -- tests/checkout.test.js
# Or a custom check
cat > /tmp/check.sh <<'EOF'
#!/bin/sh
npm ci --silent || exit 125 # can't build: skip this commit
node scripts/check-total.js | grep -q "total: 1499"
EOF
chmod +x /tmp/check.sh
git bisect run /tmp/check.sh
Tips
- Write a small failing test for the bug first; it's the perfect bisect script and becomes a regression test afterwards.
- Keep the test script outside the repo (or untracked), so checking out old commits doesn't change it.
git bisect logshows the steps so far;git bisect visualizeshows remaining candidates.- Small, focused commits make the result far more useful: "this 10-line commit broke it" beats "this 3,000-line merge broke it".
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.