Find a bad commit with git bisect run
Use a test script with git bisect run to find the first bad commit and skip revisions the script cannot test.
Your test passes on a commit from last month and fails on main, with ten commits from the good endpoint to the bad one. You can check out the middle one, run the test, type git bisect good or git bisect bad, and repeat. Git can run that loop for you.
Give bisect a command
git bisect run takes any command and runs it on each commit that bisect checks out. In my throwaway repo, test.mjs imports sum, prints ok when sum(2, 3) is 5, and exits 1 otherwise. I name the bad end first and the good end second.
$ git bisect start HEAD HEAD~9
Bisecting: 4 revisions left to test after this (roughly 2 steps)
$ git bisect run node test.mjs
running 'node' 'test.mjs'
ok
Bisecting: 2 revisions left to test after this (roughly 1 step)
running 'node' 'test.mjs'
FAIL: sum(2, 3) = -1
Bisecting: 0 revisions left to test after this (roughly 0 steps)
running 'node' 'test.mjs'
FAIL: sum(2, 3) = -1
aec674e8d1094200960906a214e06c178c44ccea is the first bad commit
c6: refactor sum
bisect found first bad commitTen commits took three runs of the test, and bisect named c6: refactor sum without me touching the keyboard. Use git show with the reported hash to inspect the bad commit. Run git bisect reset when you finish to return to main.
Exit codes decide the verdict
Bisect reads one thing from your command, the exit code. 0 marks the commit good. Codes 1–124, 126 and 127 marks it bad; I ran 1, 2, 99 and 124 and each one found the commit.
Two codes are special. 125 tells bisect to skip a commit you cannot judge. Anything from 128 up stops the whole run, so Ctrl-C (exit 130) ends the bisect with exit code 130 ... is < 0 or >= 128 and marks nothing.
A typo in the script path exits 127. If the command exits 126 or 127, Git also tries it on a known-good revision. A 126 or 127 there produces a bogus-exit-code error. Try the command on your good revision before starting the run. A missing test.mjs behaves differently: Node can exit 1 and Git will count that as a failed test.
Skip commits that cannot run
Some commits in a range will not build. If the test fails on those, bisect blames them. I guard the test with a syntax check and return 125 when the code cannot run.
#!/bin/sh
node --check sum.mjs 2>/dev/null || exit 125
node test.mjsIn a second repo, c2 had a syntax error and c3 had the wrong math. Running git bisect run ./check.sh skipped c2, marked c3 bad, and then stopped with a list instead of one answer:
There are only 'skip'ped commits left to test.
The first bad commit could be any of:
1bd01236536e34b7625bcd2c0b54c64100276177
ee9e510c606f093706b0ebdd07022442c4caad8f
We cannot bisect more!The bug is in c2 or c3, and the skipped commit sits too close to tell. I open both diffs and read them. The bisect docs have the full reference.