git bisect - Hunt the Bad Commit
git bisect - binary search your history
Scenario: A test passed last week but fails today, and there are 200 commits in between - any one of which could be the culprit. Checking each by hand, one at a time, could take all day. git bisect instead does a binary search through your commit history: about 8 checks is enough to pinpoint the exact bad commit out of 200, because each check eliminates half of the remaining suspects.
$ git bisect start
$ git bisect bad # current commit is broken
$ git bisect good v1.2.0 # this old tag/commit was known to work
# Git checks out a commit exactly halfway between good and bad. Test it, then tell Git:
$ git bisect good # or: git bisect bad
# ...repeat until Git prints the first bad commit...
$ git bisect reset # return to where you started
Each round, you tell Git whether the commit it just checked out has the bug or not, and Git narrows the range by half again - the same idea as guessing a number between 1 and 100 by always asking "higher or lower?" rather than counting up from 1.
| Command | Meaning |
|---|---|
git bisect start | Begin a bisect session |
git bisect bad [commit] | Mark a commit as broken (defaults to HEAD if omitted) |
git bisect good [commit] | Mark a commit as known-working |
git bisect reset | End the session and go back to your original branch/commit |
git bisect run ./test.sh | Automate the whole process - Git runs the script itself to judge each commit |
Tip:git bisect run <script>fully automates the hunt: Git checks out each candidate commit in turn, runs your test script against it (exit code0means good, any non-zero means bad), and reports the exact culprit commit - completely hands-free once you've written a script that reliably detects the bug.