How to find a bug with `git bisect`?

Learn how to find bugs with the git bisect tool

Debugging is a daily part of a programmer’s job. However, like bugs themselves, bugs hide between lines of code and become apparent after several commits in git. Fortunately, git has a command that allows developers to find bugs more quickly: `git bisect`.

How does `git bisect` work?

The git bisect command is used to find and identify the commit that introduced an error in the code or bug. For this, the command uses the binary search algorithm.

Initially, the developer must specify which commit they know contains a bug, which is usually the HEAD commit. After this, mark a “good” commit, that is, the last commit in which you are sure that everything worked perfectly.

In this way, the developer sets the lowest and highest indices for the binary search. From then on, the git bisect command helps us select the commit between those two points until we narrow down the search to identify the commit responsible for having introduced an error.

How to use git bisect

On the command line, set which code is good and which is bad

Start git bisect

$ git bisect start

Set a commit where there is no bug

$ git bisect good

Set a commit where there is no bug

$ git bisect bad

Bisecting: X revisions left to test after this (roughly Y steps)
[commit-hash]
Afterwards, the process will dissect the revisions and upload them for us to verify if it is a bug-free or buggy version.

If the version works, write

$ git bisect good

If the version fails, write

$ git bisect bad

Then git bisect will respond with a message similar to this:

Bisecting: 12 revisions left to test after this (roughly 4 steps)
Each time a binary search will be performed to narrow down the options.

In case you have a script that allows you to automatically tell us if the code works or not, the debugging process can be automated with git bisect:

Run git bisect …

$ git bisect run node bisect / index.js

To learn more about how `git bisect` works, check out the documentation here or check out this video to see the program in action:

Read also: How to create tests in Ruby on Rails? (Part 1)