常见的Git崩溃场景
- 误删分支或提交
- 代码合并冲突无法解决
- 误执行
git reset --hard导致代码丢失 - 错误的
rebase操作导致历史混乱
恢复误删的分支或提交
git reflog查看操作记录,找到误删的提交哈希
git checkout -b <branch_name> <commit_hash>基于历史提交重建分支
撤销错误的git reset --hard
git fsck --lost-found检查悬空对象
git show <dangling_commit>确认丢失的提交
git merge <dangling_commit>恢复提交
解决rebase导致的混乱
git rebase --abort终止当前rebase操作
git reset --hard ORIG_HEAD回退到rebase前的状态
从冲突中恢复
git checkout --ours <file>或git checkout --theirs <file>选择保留特定版本
git merge --abort终止合并并恢复原始状态
找回丢失的未提交更改
git stash list查看暂存记录
git stash apply <stash_hash>恢复暂存的修改
修复损坏的仓库
git fsck检查仓库完整性
git gc --prune=now清理无效对象
git remote update --prune同步远程引用
预防Git灾难的建议
- 频繁提交并推送到远程仓库
- 使用
git tag标记重要版本 - 避免直接操作历史记录(如
reset、rebase)
工具辅助
gitk或git-gui可视化历史记录- 脚本自动化备份关键分支