git bisect
helps you find the commit that introduced a bug by using binary search. It allows you to efficiently identify the exact commit where things went wrong.
Initial Example
To start a bisect session, you need to mark a known bad commit and a known good commit:
$ git bisect start $ git bisect bad <bad_commit> $ git bisect good <good_commit>
BISECT Options
Option | Description |
---|---|
start | Start a bisect session. |
bad | Mark the current commit as bad (contains the bug). |
good | Mark the specified commit as good (doesn’t contain the bug). |
reset | End the bisect session and return to the original branch. |
skip | Skip the current commit if it cannot be tested (e.g., it doesn’t compile). |
run <script> | Automate the bisect process using a script that tests commits. The script should return 0 for good commits and 1 for bad commits. |
visualize | Display the remaining suspects in the bisect process using a graphical tool. |
log | Show a log of the bisect steps taken during the session. |
view | Open the current commit in the default text editor for inspection. |
--no-checkout | Do not checkout the new working tree at each iteration of the bisection process. Instead, update the reference named BISECT_HEAD to point to the commit to be tested. Useful when the test does not require a checked-out tree. If the repository is bare, this is assumed. |
--first-parent | Follow only the first parent commit upon seeing a merge commit. Useful to avoid false positives when merged branches contain broken commits but the merge itself is OK. |
Examples
1. Basic Bisect
To find the commit that introduced a bug:
- Start the bisect session:
$ git bisect start
- Mark the current commit as bad:
$ git bisect bad
- Mark an older commit as good:
$ git bisect good <good_commit>
- Git will now check out a commit in the middle. Test the commit:
- If the commit is bad, mark it as bad:
sh $ git bisect bad
- If the commit is good, mark it as good:
$ git bisect good
- Repeat the process until Git identifies the exact commit that introduced the bug.
2. Automating Bisect
You can automate the bisect process with a script:
- Run the bisect session with a script:
$ git bisect start $ git bisect bad $ git bisect good <good_commit>
- Use the
run
command to automate the testing process:
$ git bisect run <script>
- The script should return
0
for good commits and1
for bad commits.