The "git bisect" command is a handy tool for pinpointing the exact commit that introduced a bug into your code. It works by systematically narrowing down the range of commits where the code was working fine and where it's broken.
Assuming, we have to find the commit that introduced the bug, the usual way would be to checkout commit one by one and check whether it is working fine or not. Another way would be to get a list of commits that went between good and bad commits and perform a binary search manually. But, we don't have to do this manually, we can make use of the beautiful command "git bisect".
git bisect start -> to start the git bisect process.
git bisect good <commit-id> -> mark the mentioned commit-id as good.
git bisect bad <commit-id> -> mark the mentioned commit-id as bad.
git bisect good -> marks current commit as good.
git bisect bad -> marks current commit as bad.
git bisect reset -> ends the git bisect process.
Consider the following commits, we have the information that the code was working fine in the first commit but is broken in the seventh one. Now, we will use the git bisect command to figure out the commit which introduced the bug.
git bisect start
git bisect good fadce01 -> mark the first commit as good where the code was working fine.
git bisect bad 3c4fede -> mark the seventh commit as buggy where the issue is seen.
Following the previous command, the git will automatically point to the middle commit. At this step, we can do the necessary testing and conclude whether this commit has an issue or not. Based on that, we can mark the commit as good or bad.
Supposing, the commit was good, we will mark it as good using git bisect good. With this, we also conclude that all the commits that went before the 4th one are also fine. It will now point to the sixth commit.
At this point, we do the same testing to check whether the sixth commit is good or bad. Let's assume the commit is bad, we mark it bad "git bisect bad". Now it will automatically point to the fifth commit.
This is the last step. We perform the same verification steps for the fifth commit and mark it as good or bad. Let's assume it's bad. In that case, we have the confirmation that the bug was introduced by the fifth commit.
After we get the bad commit, we can now exit the git bisect process, using "git bisect reset".
The git bisect uses binary search to reduce the time taken. With more number of commits, the time taken will be significantly reduced. It is a very useful tool to find the regression bug and I would recommend you to start using it.
Thanks, for reading my post. If you like my post, please upvote and follow me :)