git/bisect

Binary Search for Bugs

Use binary search to find the specific commit that introduced a bug or regression

git
bisect
debug
search
bug
regression
automation

Command

git bisect

Explanation

`git bisect` is a powerful debugging tool that uses binary search to efficiently locate the commit that introduced a bug or regression. Instead of manually checking each commit, Git automates the process by dividing the commit history into halves. You start by marking one known "good" commit (where the bug didn’t exist) and one "bad" commit (where the bug is present). Git then checks out a midpoint commit for you to test. You label each commit as "good" or "bad" until Git isolates the exact commit that introduced the problem. This dramatically reduces the time needed to find regressions, especially in large repositories. You can also automate testing with scripts using `git bisect run` to classify commits automatically based on test results. Once the culprit is found, you can reset the repository with `git bisect reset`.

Common Use Cases

  • Finding the commit that introduced a bug or regression
  • Automating regression detection in large codebases
  • Analyzing code history to identify when specific behavior changed
  • Testing commits automatically using custom scripts

Best Practices

  • Always identify a definite good and bad commit before starting bisect
  • Automate tests when possible using `git bisect run` for consistency
  • Commit any ongoing work before starting bisect to avoid losing changes
  • Document the bisect session if debugging collaboratively
  • Use descriptive test criteria so results remain reproducible

Common Mistakes to Avoid

  • Forgetting to reset the repository after finishing bisect (`git bisect reset`)
  • Marking commits incorrectly as good or bad, which leads to inaccurate results
  • Running bisect without specifying both a good and bad commit
  • Not testing each checked-out commit properly before marking it

Troubleshooting

Problem: Accidentally marked the wrong commit as good or bad

Solution: Use `git bisect reset` to restart the bisect session and begin again.

Problem: Bisect session stuck or confusing results

Solution: Ensure your testing steps are consistent. Restart the bisect session and double-check your good/bad markers.

Problem: Want to automate bisect testing

Solution: Use `git bisect run <script>` where your script returns exit code 0 for good commits and non-zero for bad ones.

Problem: Forgot to return to original branch after bisecting

Solution: Run `git bisect reset` to end the session and restore your previous HEAD.

Examples

Start a bisect session

git bisect start

Mark the current commit as bad (bug present)

git bisect bad

Mark a known good commit (no bug)

git bisect good abc123

Automatically run a script to test commits during bisect

git bisect run ./test_script.sh

End the bisect session and return to the original branch

git bisect reset