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

git reflog 引用日志

git reflog(引用日志)记录 HEAD 指针的所有变化,可用于找回丢失的提交。

什么是 reflog

reflog 记录 Git 操作历史:

  • 每次 commit、checkout、reset、merge 等
  • HEAD 指针的每次移动
  • 即使提交被"删除"也保留记录
  • 默认保留 90 天

基本用法

Bash
# 查看 reflog
git reflog

# 查看指定分支的 reflog
git reflog show branch-name

# 查看更多历史
git reflog --all

reflog 输出示例

Bash
$ git reflog
a1b2c3d (HEAD -> main) HEAD@{0}: commit: 添加新功能
b2c3d4e HEAD@{1}: commit: 修复bug
c3d4e5f HEAD@{2}: checkout: moving from feature to main
d4e5f6g HEAD@{3}: commit: 功能开发中
e5f6g7h HEAD@{4}: reset: moving to HEAD~1
f6g7h8i HEAD@{5}: commit: 原始提交

reflog 记录格式

Bash
<commit-hash> HEAD@{<index>}: <operation>: <message>

示例解读:
a1b2c3d HEAD@{0}: commit: 添加新功能
      ↑         ↑         ↑       ↑
   提交哈希   索引号    操作类型  操作说明

常见操作记录

操作reflog 记录
commitcommit: 提交信息
checkoutcheckout: moving to branch
resetreset: moving to commit
mergemerge: 合并信息
rebaserebase: 变基信息
pullpull: 拉取信息

找回丢失提交

Bash
# 场景:误用 reset --hard 丢失提交
$ git reset --hard HEAD~2
# 提交 a1b2c3d 和 b2c3d4e 被"删除"

# 查看 reflog 找到丢失提交
$ git reflog
a1b2c3d HEAD@{0}: reset: moving to HEAD~2  # 刚才的 reset
b2c3d4e HEAD@{1}: commit: 添加新功能       # 丢失的提交
c3d4e5f HEAD@{2}: commit: 修复bug          # 丢失的提交

# 恢复到丢失的提交
git reset --hard b2c3d4e

# 或创建新分支保存
git checkout -b recovery b2c3d4e

使用 HEAD@{n} 引用

Bash
# 使用 reflog 索引引用提交
git checkout HEAD@{2}
git reset --hard HEAD@{5}

# 查看 HEAD@{2} 的详细信息
git show HEAD@{2}

reflog 常用场景

恢复误删提交

Bash
# 误删提交后恢复
git reflog           # 找到提交
git reset --hard <commit>

恢复误删分支

Bash
# 分支被删除
git branch -D feature

# 找到分支最后的提交
git reflog
# 找到 checkout: moving from feature to main

# 恢复分支
git checkout -b feature <commit>

撤销错误 reset

Bash
# 误操作 reset
git reset --hard HEAD~5

# 撤销这个 reset
git reflog
git reset --hard HEAD@{1}

查看操作历史

Bash
# 查看最近的操作
git reflog -10

# 查看所有分支的操作
git reflog --all

reflog 配置

text
# 设置过期时间
git config gc.reflogExpire 90  # 默认 90 天
git config gc.reflogExpireUnreachable 30

# 手动清理过期记录
git reflog expire --expire=30.days.ago --all

# 禁用 reflog(不建议)
git config core.logAllRefUpdates false

reflog 与 git log 区别

特性refloglog
记录内容HEAD 移动历史提交历史
可见范围本地操作所有提交
丢失提交可找回无法看到
过期机制有(90天)

reflog 是 Git 的安全网,误操作后第一时间用 reflog 找回。

要点总结

  1. reflog 记录 HEAD 的每次移动
  2. 使用 git reflog 查看操作历史
  3. HEAD@{n} 引用历史位置
  4. 可找回"丢失"的提交和分支
  5. 默认保留 90 天,可配置过期时间

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

← 上一篇 git bisect 二分查找
下一篇 → git revert 撤销提交
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

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

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