Binary Search for Bug-Introducing Commits with Bisect
Use git bisect to perform an efficient binary search through commit history and pinpoint the exact commit that introduced a bug.
Prerequisites
- -Git installed
- -A known good commit where the bug did not exist
- -A way to test whether the bug is present (manual or script)
Steps
Start the bisect session
Initialize bisect mode. Git will guide you through a binary search of commits between a known good and bad state.
Mark the current commit as bad
Tell Git that the current HEAD contains the bug. This sets the upper bound of the search range.
You can also specify a commit hash: 'git bisect bad <hash>' if HEAD is not the bad commit.
Mark a known good commit
Provide a tag, branch, or commit hash where the bug was not present. Git will now check out the midpoint between good and bad.
If unsure which commit was good, try a commit from a few weeks ago and narrow down from there.
Test and mark each bisect step
Git checks out a commit halfway between good and bad. Test it, then mark it. Git halves the range each time, finding the culprit in O(log n) steps.
If a commit cannot be tested (e.g., it does not build), use 'git bisect skip' to skip it. Git will try a nearby commit instead.
Automate bisect with a test script
Provide a command that exits 0 for good and non-zero for bad. Git will run it at each step automatically until it finds the first bad commit.
You can use any script: 'git bisect run ./test-bug.sh'. The script must be in the working tree or an absolute path.
End the bisect session
Return to the original HEAD and end bisect mode. Git will output the first bad commit hash before resetting.
Full Script
FAQ
Discussion
Loading comments...