git bisect

Even when adhering to strong design principles, let’s face it: nobody’s perfect and things do go wrong. It can sometimes be difficult to track down the commit that caused a particular behavior change in an application. In some cases it may be a combination of multiple factors.

How to use git bisect

Have you ever noticed a bug or regression in your codebase and wondered, “which exact commit introduced this?” This is the use case for git bisect. Here is how to use it:

1. Find the good commit id

Find a commit from back in your history for which the bug/regression/whatever had not yet manifested. Remember the commit id.

2. Check out the latest “bad” commit

Ensure you’ve checked out the “bad” commit. This means any commit where your issue manifests itself. Hint: it’s easier to stay organized if it’s the top commit of a branch.

3. Start the bisect interface

Tell git that you want to start “bisecting” by running:

git bisect start

4. Tell git some commit that’s “good”

Let git know of a commit where your bug does not manifest by running:

git bisect good GOOD_COMMIT

Here, GOOD_COMMIT needs to be a reference to the commit that you know was good.

5. Tell Git some commit that’s “bad”

You’ve already checked out the bad commit – i.e a commit where your bug manifests itself. To let git know this commit is bad, run:

git bisect bad

6. Follow the prompts (repeating step)

Git will now immediately find and check out the commit that is halfway between your good commit and your bad commit. Run your specs, do your acceptance test(s), etc., to see if the commit has the issue you’re trying to track down or not.

If the issue is still present, run:

git bisect bad

If the issue is fixed in the current commit, run

git bisect good

7. Git tells you which commit the behavior started in

Repeat this step until Git lets you know which commit is the first “bad” one. Make a note of the commit ID or tag it, etc. Now you can inspect the commit and see what changes were made to break things, etc.

8. Go back to the way things were before you started bisecting

Remember to go back to the way things were before you started git bisect. You can do this by running

git bisect reset