git bisect 与 blame
约 649 字大约 2 分钟
布欧-Lewyon
2026-05-15
首页 › Git › 工具与技巧(在新窗口打开) › git bisect 与 blame
git bisect
二分查找引入 Bug 的提交,将问题定位从 N 次排查减少到 log2(N) 次。
# 启动 bisect
git bisect start
# 标记当前版本为坏(有 Bug)
git bisect bad
# 标记一个过去的好版本(无 Bug)
git bisect good v1.0
# Git 自动切到一个中间版本
# Bisecting: 12 revisions left to test after this (roughly 4 steps)
# 测试当前版本
# - 如果有 Bug:git bisect bad
# - 如果正常:git bisect good
# 重复 4 步后,Git 找到第一个引入 Bug 的提交
# a1b2c3d is the first bad commit自动化 bisect
# 使用脚本自动测试
git bisect start HEAD v1.0
git bisect run npm test # 测试脚本返回 0 为 good,非 0 为 bad
git bisect reset
# 更复杂的脚本
git bisect run ./run-test.sh
# run-test.sh:
# #!/bin/bash
# npm test || exit 1完整流程
git bisect start
git bisect bad # 当前版本有 Bug
git bisect good v2.0 # v2.0 是好的
# Git 跳到中间版本
# 测试...
git bisect good # 这个版本没问题
# Git 跳到更近的版本
# 测试...
git bisect bad # 这个版本有 Bug
# ...
# a1b2c3d is the first bad commit
git bisect reset # 恢复到原分支git blame
逐行查看文件的每一行是谁、什么时间、在哪个提交中修改的:
# 基本用法
git blame README.md
# a1b2c3d (张三 2026-05-15 10:00:00 +0800 1) # My Project
# d4e5f6f (李四 2026-05-15 11:00:00 +0800 2) print("hello")
# 只显示前 N 行
git blame -L 10,20 README.md
# 显示邮箱
git blame -e README.md
# 忽略空白变更
git blame -w README.md
# 显示修改的日期
git blame --date=short README.mdblame 场景
# 找到某行代码的最后修改者
git blame -L 42,42 src/main.py
# a1b2c3d (张三 2026-05-14) main.py:42 def process():
# 查看某段代码的修改历史
git log -p -L 42,50:src/main.pygit grep
在仓库中搜索文本内容:
# 搜索字符串
git grep "function_name"
# 正则搜索
git grep -n "TODO|FIXME"
# 只搜索特定文件类型
git grep -- "*.py" "def test"
# 查看匹配行数统计
git grep --count "import" -- "*.py"git shortlog
按作者汇总提交:
# 查看每个作者的提交数
git shortlog -sn
# 5 张三
# 3 李四
# 2 王五
# 生成 ChangeLog
git shortlog -sn --no-merges v1.0..v2.0小结
git bisect二分查找 Bug 引入的提交,git bisect run可自动化。git blame逐行追溯代码的最后修改者和提交。git grep在仓库中搜索内容,比grep -r更快(只搜索 Git 跟踪的文件)。git shortlog -sn按作者汇总提交数,适合生成 Release Notes。
