Git bisect
is a powerful tool that helps you find the exact commit where a bug was introduced in your codebase. It uses a binary search algorithm to quickly narrow down the problematic commit.
How Git Bisect Works
Imagine you have a project with 100 commits. You know that:
- At commit #1, the feature worked fine.
- At commit #100, the feature is broken.
Git bisect will:
- Check out the middle commit (#50).
- Ask you to test if the bug exists there.
- Based on your answer, it will then check either #25 or #75.
- Repeat this process until it finds the exact commit where the bug appeared.
Basic Usage Example
Let's walk through a practical example:
- Start the bisect session:
git bisect start
- Mark the current commit as bad (where the bug exists):
git bisect bad
- Mark an older commit as good (where the bug didn't exist):
git checkout <good-commit-hash>
git bisect good
Or combine steps 2 and 3 in one command:
git bisect start <bad-commit> <good-commit>
- Git will now checkout a commit in the middle. Test your code to see if the bug exists:
If the bug exists:
git bisect bad
If the bug doesn't exist:
git bisect good
Repeat step 4 until git identifies the first bad commit.
When finished, reset your repository:
git bisect reset
Best Tips and Tricks
- Automate testing: Instead of manually testing each commit, you can provide a script:
Create a test script:
#!/usr/bin/env python3
import sys
from calculator import calculate # Our function to test
# Test case - should return 42
result = calculate(40, 2)
expected = 42
if result == expected:
sys.exit(0) # Success - mark as good
else:
sys.exit(1) # Failure - mark as bad
Make it executable:
chmod +x test-script.py
Run the script:
git bisect run ./test-script.py
Note: The script should exit with 0 for good commits and non-zero for bad commits.
- Skip commits: If a commit can't be tested (maybe it doesn't compile), skip it:
git bisect skip
- Visualize progress:
git bisect log
git bisect visualize
Narrow down faster: Try to pick good and bad commits that are as far apart as possible initially.
Use tags: If you know approximate versions where it worked/didn't work:
git bisect start v2.0.0 v1.9.0
- Check the diff: Once you find the bad commit, examine what changed:
git show <bad-commit>
- Document findings: After finding the problematic commit, consider adding a test case to catch similar issues in the future.
Key Takeaways:
✅ Fast & Efficient – Instead of checking every commit, git bisect smartly halves the search space each time.
✅ Flexible – Works with manual testing or automated scripts (git bisect run).
✅ Precise – Pinpoints the exact commit, making it easier to understand and fix the issue.
Up Next: Day 5: git worktree
– Work on multiple branches simultaneously
Daily advance GIT tips in your inbox—worth starting? Respond to my poll here🚀
For more useful and innovative tips and tricks, Let's connect on Medium