全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-11 7 分钟 ✍️ juanwangdev

git bisect 二分查找

git bisect 使用二分搜索算法快速定位引入问题的提交。

什么是 git bisect

bisect 在提交历史中进行二分查找:

  • 指定一个好提交(无 bug)
  • 指定一个坏提交(有 bug)
  • Git 自动二分定位
  • 快速找到引入问题的提交

bisect 原理

Bash
提交历史:
A → B → C → D → E → F → G → H
↑                       ↑
好                      坏(有 bug)

二分过程:
第一次:检查 E(中间)
  - E 好:问题在 F-G-H
  - E 坏:问题在 B-C-D-E

继续二分直到找到引入问题的提交

基本用法

Bash
# 开始 bisect
git bisect start

# 标记坏提交(当前有 bug)
git bisect bad

# 标记好提交(已知无 bug)
git bisect good <good-commit>

# Git 会自动跳转到中间提交
# 测试当前版本

# 标记当前版本
git bisect good  # 当前版本无 bug
git bisect bad   # 当前版本有 bug

# 找到后结束
git bisect reset

bisect 示例

Bash
# 场景:v1.0 正常,当前版本有 bug

$ git bisect start
$ git bisect bad          # 当前版本有 bug
$ git bisect good v1.0    # v1.0 正常

Bisecting: 3 revisions left to test after this
[abc123] 提交信息

# 测试 abc123 版本
$ npm run test

# 标记结果
$ git bisect good  # abc123 正常

Bisecting: 1 revision left to test after this
[def456] 提交信息

# 测试 def456 版本
$ git bisect bad   # def456 有 bug

Bisecting: 0 revisions left to test after this
[ghi789] 提交信息

# ghi789 是第一个坏提交!
$ git bisect reset
# 回到原始状态

使用自动化脚本

Bash
# 自动运行测试脚本
git bisect start
git bisect bad
git bisect good v1.0
git bisect run npm test

# 或指定脚本
git bisect run ./test-script.sh

# 自动完成所有测试

自动化脚本示例

Bash
#!/bin/bash
# test-script.sh

npm run build
if npm run test; then
    exit 0  # 好:测试通过
else
    exit 1  # 坏:测试失败
fi
Bash
# 运行 bisect
git bisect start HEAD v1.0
git bisect run ./test-script.sh

# 输出
abc123 is the first bad commit
commit abc123
Author: Developer
Date: Mon May 11

    引入 bug 的提交信息

bisect 常用命令

命令说明
bisect start开始二分
bisect bad标记坏提交
bisect good标记好提交
bisect skip跳过当前(无法判断)
bisect reset结束并返回
bisect log查看 bisect 日志
bisect visualize图形化显示
bisect run自动测试

跳过无法判断的提交

Bash
# 某些提交无法判断(如构建失败)
git bisect skip

# Git 会选择其他提交继续

查看 bisect 进度

Bash
# 查看当前状态
git bisect log

# 图形化查看
git bisect visualize
git bisect view

快速开始 bisect

Bash
# 简化启动
git bisect start HEAD v1.0
# HEAD 是坏,v1.0 是好

# 一行命令
git bisect start HEAD v1.0 --first-parent

bisect 结束后

text
# 查看找到的提交
git show <bad-commit>

# 分析问题原因
git diff <bad-commit>^ <bad-commit>

# 修复问题
# 创建修复提交

# 结束 bisect
git bisect reset

bisect 效率

text
假设 1000 个提交:
线性查找:需要测试 ~1000 次
二分查找:需要测试 ~10 次(log2(1000))

效率提升:~100倍

bisect 是定位历史 bug 的利器,配合自动化测试效率极高。

要点总结

  1. 指定好提交和坏提交开始 bisect
  2. Git 自动跳转到中间提交
  3. 测试后标记 good 或 bad
  4. bisect run 可自动化测试
  5. 找到后用 bisect reset 返回

📝 发现内容有误?点击此处直接编辑

← 上一篇 团队协作规范
下一篇 → git reflog 引用日志
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库