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 记录 |
|---|---|
| commit | commit: 提交信息 |
| checkout | checkout: moving to branch |
| reset | reset: moving to commit |
| merge | merge: 合并信息 |
| rebase | rebase: 变基信息 |
| pull | pull: 拉取信息 |
找回丢失提交
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 区别
| 特性 | reflog | log |
|---|---|---|
| 记录内容 | HEAD 移动历史 | 提交历史 |
| 可见范围 | 本地操作 | 所有提交 |
| 丢失提交 | 可找回 | 无法看到 |
| 过期机制 | 有(90天) | 无 |
reflog 是 Git 的安全网,误操作后第一时间用 reflog 找回。
要点总结
- reflog 记录 HEAD 的每次移动
- 使用
git reflog查看操作历史 - HEAD@{n} 引用历史位置
- 可找回"丢失"的提交和分支
- 默认保留 90 天,可配置过期时间
📝 发现内容有误?点击此处直接编辑