git bisect
Learn the git bisect command to binary-search your commit history and find the exact commit that introduced a bug. Includes automation with run.
Definition
The git bisect command helps you find the exact commit that introduced a bug by performing a binary search through your history. You tell Git one commit where the code worked ("good") and one where it is broken ("bad"), and Git repeatedly checks out the midpoint for you to test, halving the suspect range each time until a single culprit remains.
Why binary search
If a bug appeared somewhere in the last 1,000 commits, checking them one by one would be exhausting. Binary search needs only about ten tests to pinpoint the offender, because each answer cuts the remaining candidates in half. git bisect automates the bookkeeping so you only have to answer "does it work here?"
Starting a bisect session
Begin the session, then mark the current broken state and a known-good past commit:
git bisect start
git bisect bad # the current commit is broken
git bisect good v1.4.0 # this tag was known to workGit checks out a commit halfway between them. You build and test that revision, then report the result:
git bisect good # this commit works — bug is newer
# or
git bisect bad # this commit is broken — bug is here or olderRepeat until Git announces the first bad commit.
Ending the session
When Git reports the culprit, return to where you started:
git bisect resetThis restores HEAD to the branch you were on before bisecting.
Automating with git bisect run
If you can express the test as a script or command that exits 0 for good and non-zero for bad, Git will run the entire search unattended:
git bisect start HEAD v1.4.0
git bisect run npm testGit checks out each midpoint, runs the command, interprets the exit code, and stops on the first failing commit — no manual marking required.
Common options
| Command | Description |
|---|---|
git bisect start | Begins a bisect session. |
git bisect bad [<commit>] | Marks a commit as broken (defaults to current). |
git bisect good [<commit>] | Marks a commit as working. |
git bisect skip | Skips a commit that cannot be tested (for example, it does not build). |
git bisect run <cmd> | Automates the search using a test command's exit code. |
git bisect reset | Ends the session and restores the original HEAD. |
Practice
How does 'git bisect' locate a bad commit?