You know a bug was introduced somewhere between two commits. One commit is working fine (good), and the other is failing (bad). You need to find the exact commit that introduced the bug.
-
Start the bisect process:
First, tell Git which commit is good and which one is bad.git bisect start git bisect bad HEAD # Mark the current commit (HEAD) as bad git bisect good <good_commit_hash> # Mark a known good commit
For example:
git bisect bad HEAD git bisect good 7907b1b # The first commit is known to be good -
Git will check out a commit halfway between the good and bad commits.
Test the code to see if the bug still exists. -
Mark the result:
- If the bug exists, mark the commit as bad:
git bisect bad
- If the bug does not exist, mark the commit as good:
git bisect good
- If the bug exists, mark the commit as bad:
-
Repeat the process:
Git will continue narrowing down the range, checking out commits in the middle, until it finds the first bad commit. -
Once found, Git will tell you the exact commit that introduced the bug:
<commit_hash> is the first bad commit
-
Finish the bisect process:
After finding the bad commit, run:git bisect reset
This returns you to the branch you were on.
$ git bisect start
$ git bisect bad HEAD
$ git bisect good 7907b1b
# Git checks out a commit halfway between 7907b1b and HEAD
# Test the code, then mark the commit:
$ git bisect bad
# Repeat until Git identifies the bad commit
$ git bisect resetIf you have an automated test to detect the bug, you can run git bisect with a test script:
git bisect run ./test-script.shThis will automatically run your script and mark commits as good or bad based on the test result.
For a more in-depth explanation and smarter approaches to bug localization with Git Bisect, check out my full article:
Debugging with Git Bisect: A Smarter Approach to Bug Localization
- LinkedIn - Vitalii Semianchuk
- Telegram - @jsmentorfree - We do a lot of free teaching on this channel! Join us to learn and grow in web development.
- Tiktok - @jsmentoring Everyday new videos
MIT License
Copyright (c) 2024 Vitalii Semianchuk