git bisect
- Version
- 2.51
- Review
- Draft
Summary#
git bisect binary-searches history for the commit that changed a result. Mark one bad and one good commit; bisect run then tests candidates with a command. Use exit status 0 for good, 1 for bad and 125 to skip an untestable commit. Other statuses from 1 to 127 can also mark a commit bad. Reserve 126 and 127 for execution errors. Statuses of 128 or higher stop the search.
Syntax#
git bisect start BAD GOOD
git bisect run ./test-script
git bisect reset
Example#
(
set -eu
scratch=$(mktemp -d "${TMPDIR:-/tmp}/devlookup-git.XXXXXX")
trap 'rm -rf -- "$scratch"' EXIT
unset GIT_CONFIG_GLOBAL $(git rev-parse --local-env-vars)
export GIT_CONFIG_NOSYSTEM=1 GIT_TEMPLATE_DIR= LC_ALL=C
export HOME="$scratch" XDG_CONFIG_HOME="$scratch" GIT_ATTR_NOSYSTEM=1
export GIT_PAGER=cat GIT_EDITOR=true
git init -q -b trunk "$scratch/work"
cd "$scratch/work"
git config user.name "Reference Example"
git config user.email example@example.invalid
for step in 1 2 3 4 5 6 7 8; do
printf '%s\n' "$step" > step.txt
if [ "$step" -ge 6 ]; then echo broken > state.txt; else echo ok > state.txt; fi
git add step.txt state.txt
git commit -qm "Step $step"
done
# Keep the test outside the repository so checkouts cannot change it.
printf '%s\n' 'grep -qx ok state.txt' > "$scratch/check.sh"
git bisect start HEAD HEAD~7 > /dev/null
git bisect run sh "$scratch/check.sh" > /dev/null
git log -1 --format='first bad: %s' refs/bisect/bad
git bisect reset > /dev/null 2>&1
git branch --show-current
)
Expected output#
first bad: Step 6
trunk
Common mistakes#
A failure unrelated to the bug, such as a broken build, still counts as bad if the command exits with an ordinary failure status, and misleads the search. Return 125 for untestable revisions. Keep a temporary test script outside the working tree so checkouts do not change it, and run git bisect reset when you finish.
Version applicability#
Git 1.5.1 added bisect run, Git 1.5.4 added skipping, and Git 2.36 began checking the known-good revision after an initial status of 126 or 127.
The complete example requires Git 2.28 or later for git init -b.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0