Git Bisect
Something worked last month and is broken today, with 200 commits in between. Which one broke it? git bisect finds it by binary search: it checks out the commit in the middle, you say "good" or "bad", and it halves the range each time. 200 commits need only about 8 tests (2⁸ = 256).
The manual workflow
bash
git bisect start
git bisect bad # the current commit is broken
git bisect good v1.2 # this older version worked
# Git checks out a commit in the middle: test it, then
git bisect good # or: git bisect bad
# ... repeat until Git prints "<hash> is the first bad commit"
git bisect reset # return to where you startedA bisect session
Here a repository has 8 commits; one of them breaks a price calculation. Each step marks the checked-out commit by running the check by hand:
bash · try it yourself
mkdir shop && cd shop && git init -q
echo 'price() { echo $(( $1 * 120 / 100 )); }' > price.sh
git add . && git commit -q -m "Add price with 20% tax"
git tag v1.0
for n in 2 3 4 5 6 7 8; do
echo "# note $n" >> notes.txt
if [ "$n" = 5 ]; then sed -i 's/120/102/' price.sh; fi # the bug sneaks in
git add . && git commit -q -m "Change $n"
done
check() { source ./price.sh; [ "$(price 100)" = 120 ]; }
git bisect start
git bisect bad HEAD
git bisect good v1.0 | head -1
for step in 1 2 3; do
if check; then result=good; else result=bad; fi
echo "testing $(git log -1 --format=%s): $result"
out=$(git bisect $result); echo "${out%%