git bisect: Use binary search to find the commit that introduced a bug

“git bisect” is a powerful command in Git that uses a binary search algorithm to help identify the specific commit that introduced a bug or regression in a project’s history. It automates the process of pinpointing the faulty commit by intelligently traversing the commit graph.

Here are the key features and steps involved in using “git bisect”:

  • Binary Search: “git bisect” utilizes a binary search algorithm, similar to searching for a value in a sorted list, to efficiently narrow down the range of commits that may contain the bug. It divides the commit history into halves and selects a commit in the middle to test.
  • Manual Testing: After specifying the starting and ending points for the search, typically a known “good” commit and the latest commit, you manually test each selected commit to determine if it is “good” or “bad” (contains the bug). You mark the commit as “good” or “bad” using “git bisect good” or “git bisect bad” respectively.
  • Automated Navigation: Based on your assessment of each commit, “git bisect” automatically navigates through the commit history, selecting the next commit to test based on the binary search algorithm. It jumps back and forth in the commit graph, progressively narrowing down the range of potential faulty commits.
  • Repeat and Refine: The process continues iteratively until “git bisect” identifies the specific commit that introduced the bug. At this point, it will report the faulty commit and mark it as the “bad” commit.
  • Debugging and Fixing: Once the faulty commit is identified, you can inspect the changes introduced by that commit, debug the code, and work towards fixing the issue. The information provided by “git bisect” helps in understanding the cause of the bug and streamlines the debugging process.

“git bisect” is a valuable tool for efficiently identifying the commit that introduced a bug or regression in a Git repository. By automating the search process using a binary search algorithm, it saves time and effort in pinpointing the faulty commit. This command is particularly useful when dealing with larger codebases and complex commit histories.

git bisect Command Examples

1. Start a bisect session on a commit range bounded by a known buggy commit, and a known clean (typically older) one:

# git bisect start bad_commit good_commit

2. For each commit that git bisect selects, mark it as “bad” or “good” after testing it for the issue:

# git bisect [good|bad]

3. After git bisect pinpoints the faulty commit, end the bisect session and return to the previous branch:

# git bisect reset

4. Skip a commit during a bisect (e.g. one that fails the tests due to a different issue):

# git bisect skip

5. Display a log of what has been done so far:

# git bisect log
Related Post