Skip to content

🔍 Binary Search: git bisect

Understanding in One Sentence

You have 500 commits, and a bug appeared recently. git bisect uses binary search to automatically pinpoint which commit introduced the bug — from 500 commits, it takes at most 9 tests to find the culprit (log₂500 ≈ 9).

Basic Usage

bash
# Start binary search
git bisect start

# Mark the current version as "bad" (has a bug)
git bisect bad

# Mark a known "good" version (no bug)
git bisect good v1.0        # Using a tag
git bisect good abc1234     # Using a commit hash
git bisect good HEAD~200    # Using a relative reference

Bisecting: 100 revisions left to test after this (roughly 7 steps)
[def4567890123456789012345678901234567890] fix: update dependencies

# Git automatically checks out the middle commit
# Now you test whether this version has the bug
# If this version is good:
git bisect good

# If this version is bad:
git bisect bad

# Git continues bisecting until it finds the commit that introduced the bug
abc1234 is the first bad commit
commit abc1234
Author: Someone
Date:   Mon Jan 20 10:00:00 2025 +0800

    refactor: rewrite authentication module

# End bisect, return to the original branch
git bisect reset

Automated Bisect (Even More Powerful)

If you have a test script that can determine whether a version is good or bad, you can have git bisect run fully automatically:

bash
# Write a test script (exit code 0=good, non-zero=bad)
cat > /tmp/test.sh << 'EOF'
#!/bin/bash
npm test 2>&1 | tail -5
# If tests pass (exit 0), git considers it good
# If tests fail (exit non-zero), git considers it bad
EOF
chmod +x /tmp/test.sh

# Automated binary search
git bisect start HEAD v1.0
git bisect run /tmp/test.sh

# Git automatically checks out, runs tests, marks good/bad
# A few minutes later, it tells you the result:
abc1234 is the first bad commit
bisect run success

git bisect reset

# You can also run it as a single command
git bisect start HEAD v1.0 -- npm test

💡 Tip: Real-world scenarios:

  • Performance regression: write a script to test response times, git bisect run ./test-perf.sh
  • UI regression: use Selenium to compare screenshots
  • Build failure: write a script make && echo OK || exit 1