1. Home
  2. Blog
  3. DevOps

DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect finds the commit that introduced a bug by binary search: you mark one good commit and one bad commit, and Git halves the range until one commit is left. With git bisect run and a test script it happens automatically. In our test it found 1 bad commit among 41 in just 5 runs.

9 min read
Git bisect explained: find the bad commit

Key takeaways

  • Git bisect uses binary search: about log₂(N) tests find the bad commit among N commits.
  • Our run found the bug among 41 commits in 5 test runs, about what log₂(41) ≈ 5.4 predicts.
  • git bisect run <script> automates everything: exit 0 means good, 1 to 127 (except 125) means bad.
  • Exit code 125 skips commits that cannot be tested; always finish with git bisect reset.

“It worked last month.” Somewhere in the hundreds of commits since then, something broke a calculation, slowed a page or failed a test. Reading every diff would take hours. Git bisect turns this into a short, mechanical search, and with a test script it needs no human at all. We built a repository with a hidden bug and ran every command below on Git 2.56, using a demo identity.

What does git bisect do?

You give Git two facts: a commit where the code is bad (usually the current one) and an older commit where it was good, such as the last release tag. Git checks out the commit halfway between them and asks you to test it. Your answer removes half of the remaining commits. Git repeats until a single commit remains: the first bad commit, the one that introduced the change.

Why it is so fast

Commits in range Tests needed (about log₂ N)
40 6
1,000 10
10,000 14
100,000 17

Each test halves the search space, so the number of tests grows very slowly. Even a year of busy history takes only a dozen or so checks, where checking every commit in order could take thousands.

Our test repository

We created a tiny pricing module with a check script, tagged it v1.0, then added 40 more commits. Most only touched a notes file, but one, labelled “Refactor pricing helpers”, quietly changed the formula:

# price.py at v1.0
def total(price, qty):
    return price * qty

# check.py: exit 0 if correct, 1 if broken
import sys
from price import total
sys.exit(0 if total(100, 3) == 300 else 1)
commits: 41
HEAD check exit: 1

The check fails on the latest commit. We know v1.0 was fine. The question is which of the 40 commits in between broke it, and the innocent-looking commit message would not help anyone reading the log.

Manual bisect, step by step

git bisect start
git bisect bad              # current commit is broken
git bisect good v1.0        # this tag was fine

Git can also take both in one line, git bisect start HEAD v1.0, which printed:

[4d7c735...] Docs update 21

Git checked out the middle commit. Now you test it, by running the app, the failing test or python check.py, and report the result with git bisect good or git bisect bad. Git jumps to the middle of the remaining range each time, telling you how many steps are left. After the last answer it prints the first bad commit with its message and changed files. The whole session is a loop of “test, then say good or bad”.

Tip: mark the good commit as close to the bug as you honestly can. A release tag from last week beats the first commit of the project, and it means fewer steps.

Automating it with git bisect run

If a command can tell good from bad, Git can do the whole search for you:

git bisect start HEAD v1.0
git bisect run python check.py
Bisecting: 9 revisions left to test after this (roughly 3 steps)
Bisecting: 4 revisions left to test after this (roughly 2 steps)
Bisecting: 2 revisions left to test after this (roughly 1 step)
Bisecting: 0 revisions left to test after this (roughly 0 steps)
commit 127582b...
    Refactor pricing helpers
 price.py | 2 +-
bisect found first 'bad' commit

Git ran the script 5 times in total and named “Refactor pricing helpers” as the culprit, together with the file it changed. No human decisions were needed. Any command works: a single pytest test (git bisect run pytest tests/test_price.py -q), an npm script, a shell script that builds and checks output, or a timing check for performance regressions.

How exit codes are read

Exit code Git treats the commit as
0 Good
1 to 127, except 125 Bad
125 Cannot be tested: skip it
Above 127 (for example a crash signal) Stop bisecting

This is why a script must signal its result through the exit code, not printed text. A script that prints “FAIL” but exits 0 will mark every commit good and send you after the wrong one.

Skipping commits that cannot be tested

Some commits do not build, or are halfway through a refactor. Mark them with git bisect skip manually, or exit with 125 from your script. We made our script skip five commits on purpose:

# check2.sh
git log -1 --format=%s | grep -q "Docs update 2[0-4]" && exit 125
python check.py

Git still found the same bad commit, this time after 7 runs instead of 5, because skipped commits give no information. If too many commits near the boundary are skipped, Git reports a list of possible culprits instead of a single one, so keep skips to a minimum.

Custom terms: old and new

“Good” and “bad” feel wrong when you are hunting for the commit that fixed something or changed a behaviour that is neither good nor bad. Choose your own words:

git bisect start --term-old=working --term-new=broken
git bisect broken HEAD
git bisect working v1.0
git bisect terms
Your current terms are 'working' for the old state
and 'broken' for the new state.

The built-in pair old and new also exists, which is handy for finding when a fix landed: mark the old behaviour as “old” and the fixed behaviour as “new”.

Log, replay and reset

git bisect log      # every decision so far
git bisect replay file.log
git bisect reset    # return to the branch you started on

The log is a script of your answers; ours listed each git bisect good and git bisect bad step. If you make a wrong call, save the log, edit out the bad line and replay it instead of starting over. git bisect reset is essential: until you run it, your repository sits on a detached commit in the middle of history.

Writing a good bisect test

  • Test one thing. Run the single failing test, not the whole suite, so other old failures do not confuse the result.
  • Keep the script outside the repository or untracked, so checking out old commits does not change or remove it.
  • Make it deterministic. A flaky check gives random answers and a wrong result; see our flaky tests guide.
  • Handle build failures with exit 125 rather than letting them count as bad.
  • Set a timeout for performance checks, so a hanging commit exits with a bad code instead of stalling the search.

After you find the bad commit

Read the diff with git show <commit> to see exactly what changed. Then choose a fix: write a correct follow-up commit, or undo the change with git revert <commit>, which is safe on shared branches; see our git reset vs revert guide. If the fix is needed on a release branch too, copy it there with git cherry-pick. Finally, add the check you bisected with as a permanent test, so the same bug cannot return silently; that is regression testing in action, as described in our retesting vs regression testing guide.

Common mistakes

  • Forgetting git bisect reset and committing on a detached HEAD.
  • A good commit that was actually bad, which sends the search into the wrong half.
  • Uncommitted changes blocking checkouts. Commit or stash them first.
  • Scripts that print instead of exiting with the right code.
  • Squashed history. Bisect is only as precise as your commits; one huge squash gives one huge suspect. Our git squash guide explains the trade-off.

Git bisect cheat sheet

Goal Command
Start with bad and good git bisect start BAD GOOD
Mark current commit git bisect good / git bisect bad
Skip current commit git bisect skip
Automate git bisect run ./check.sh
Custom words git bisect start --term-old=X --term-new=Y
See decisions git bisect log
Redo from a log git bisect replay file
Finish git bisect reset

Final thoughts

Git bisect is one of the highest-value Git commands and one of the least used. Find a good commit and a bad one, write a small script that exits 0 or 1, and let git bisect run do the rest. In our test it searched 41 commits in 5 runs and named the guilty commit and file, even though its message gave no hint. Keep commits small and tests reliable, and every regression becomes a five-minute investigation. Keep our Git commands cheat sheet nearby for the rest.

Frequently asked questions

What does git bisect do?

It finds the commit that introduced a change by binary search. You mark a good and a bad commit, and Git checks out the middle commit repeatedly until one commit remains.

How do I automate git bisect?

Run git bisect start BAD GOOD, then git bisect run with a command that exits 0 for good commits and 1 for bad ones. Git tests each step and reports the first bad commit.

How many steps does git bisect take?

About log2 of the number of commits. Our 41-commit range took 5 test runs, and 1,000 commits would take about 10.

How do I skip a commit in git bisect?

Run git bisect skip on that commit, or exit with code 125 from a git bisect run script. Skipped commits are not used to narrow the search.

How do I stop or undo a git bisect session?

Run git bisect reset. It ends the session and returns you to the branch and commit you were on before you started.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
Software Development

HTTP Methods Explained: GET, POST, PUT, PATCH, DELETE, Tested on a Live Server

HTTP methods explained with a small server we ran: GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS, safe vs idempotent,…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Software Development

JavaScript Sort Array: Numbers, Objects, Strings and Why 10 Comes Before 5

How to sort an array in JavaScript correctly: numbers with a compare function, objects by one or more fields, strings…

Read article →
Software Development

Python String Methods: Cheat Sheet, Real Examples and the strip() Trap

Python string methods with tested examples: split, join, strip, replace, find, startswith, is-methods, casefold, partition and translate, plus the strip()…

Read article →
Software Development

Python zip() Explained: Loop Two Lists at Once, Unzip, strict=True and Traps

Python zip() pairs items from several lists in one loop. Tested examples for dicts, unzipping with *, strict=True, zip_longest, sliding…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
Software Development

UTF-8 Encoding Explained: How Text Becomes Bytes and How to Fix Garbled Text

UTF-8 encoding explained with byte-level examples we ran in Python: how characters become 1 to 4 bytes, why café turns…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Databases & SQL

Delete Duplicate Rows in SQL: 5 Safe Methods, Tested Step by Step

How to delete duplicate rows in SQL safely: find them, preview them, then remove them with ROW_NUMBER, MIN(id), EXISTS, rowid…

Read article →
Databases & SQL

SQL RANK vs DENSE_RANK vs ROW_NUMBER: Differences with Tested Examples

SQL RANK vs DENSE_RANK vs ROW_NUMBER in one table: how each handles ties, top-N per group, the second-highest salary trap…

Read article →
Software Development

JavaScript Optional Chaining (?.) Explained: 8 Examples, ?? Defaults and Traps

JavaScript optional chaining stops “Cannot read properties of undefined” errors. 8 tested examples for properties, arrays and methods, ?? vs…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Databases & SQL

SQL COALESCE Explained: Defaults, NULLIF, IFNULL vs ISNULL and Traps, Tested

SQL COALESCE explained with queries we ran in SQLite 3.50: first non-null values, empty strings, NULL in maths, NULLIF for…

Read article →
Databases & SQL

SQL Self Join Explained: Employee-Manager, Pairs and Row Comparisons, Tested

SQL self join explained with queries we ran in SQLite 3.50: employee and manager, earning more than the manager, unique…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →
Artificial Intelligence

Prompt Injection Explained: How AI Apps Get Tricked and How to Defend Them

Prompt injection explained for builders: direct and indirect attacks, why keyword filters fail (our test blocked 1 of 4), and…

Read article →
DevOps

DNS Records Explained: A, AAAA, CNAME, MX, TXT and TTL With Real Lookups

DNS records explained with lookups we ran: how resolution works, A and AAAA, CNAME rules, MX and null MX, TXT…

Read article →
DevOps

Feature Flags Explained: Safe Releases, Gradual Rollouts and Flag Hygiene

Feature flags explained with a rollout simulation we ran: flag types, percentage rollouts with stable hashing, kill switches, allow lists,…

Read article →
Test Automation

Test Data Generation With Python Faker: Realistic, Repeatable and Safe Data

Test data generation with Python Faker, run and measured: seeding for repeatable data, locales, unique values, domain-shaped records, edge cases…

Read article →
Software Testing

Shift-Left Testing Explained: Find Bugs Earlier Without Slowing the Team

Shift-left testing explained: what it means, why early defects are cheaper, practices from requirement reviews to CI checks, the tester's…

Read article →
Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →