Photo by kazuend on Unsplash

How I Found and Fixed a Bug in My Code Using Git Bisect

Ahmad Berahman
3 min readFeb 1, 2024

Hello everyone! Today, I want to share with you a story about how I identified and fixed a bug in one of my coding projects. This story is all about a powerful tool called git bisect.

The Problem

In my coding journey, I faced a challenging situation. I was working on a project with over 100 changes (we call them commits) added to the code. Everything seemed fine until I noticed a bug in the latest version of my project. This bug wasn’t there before, so I knew it was introduced by one of the recent changes. But which one?

Understanding Git Bisect

Git bisect is like a detective tool for coders. It helps us find the exact change that caused a problem. Imagine you have a row of 100 light bulbs, and one suddenly stops working.
You need to find out which bulb is the problem. Instead of checking each bulb one by one, you start in the middle. If the middle bulb works, the problem must be in the second half. If it doesn’t, the problem is in the first half.
This method is called binary search, and it’s a smart way to find issues quickly.

My Journey with Git Bisect

In my case, I knew my project was fine at the beginning (let’s call this point A1) and had a bug at the end (point A100).
To start my adventure, I first marked the current version (with the bug) as bad. Let’s call this point A100. Then, I went back to a version where I was sure everything was fine, say A1, and marked it as good.

Here’s how you can start a git bisect session:

git bisect start     # begin the bisecting session
git bisect bad # mark the current version as bad
git bisect good A1 # mark the version A1 as good

Git bisect then picked a midpoint, let’s say A50, and I tested this version. To my relief, A50 was working fine, so I marked it as good:

git bisect good

The tool then selected another point, say A75. Unfortunately, A75 had the bug, so I marked it as bad:

git bisect bad

Git bisect continued this process, narrowing down the range each time. It’s like playing a game of hot and cold to find the hidden treasure.

The Aha! Moment :))

Finally, git bisect pinpointed the exact change where the bug appeared. Let’s call this the A63 commit. I could now see the code changes in A63 by using:

git diff A62 A63

This command showed me the differences between the good (A62) and the bad (A63) commits. It was like catching the bug red-handed!

Conclusion:

Using git bisect, I turned a daunting task into a manageable and almost fun detective game. This tool not only saved me time but also taught me a valuable lesson in troubleshooting. Remember, in the world of coding, sometimes the most efficient way to find a problem is to split your search and conquer!

--

--