回滚到之前的提交有几种方法,具体取决于你的需求:
1. 临时查看(不修改历史)
bash
# 临时切换到某个提交查看(只读模式)
git checkout <commit-hash>
# 查看完毕后回到当前分支
git checkout myfoc
2. 撤销工作区的修改
bash
# 撤销所有未提交的修改
git restore .
# 或者使用旧命令
git checkout -- .
3. 软回滚(保留修改内容)
bash
# 回滚到指定提交,但保留所有修改在暂存区
git reset --soft <commit-hash>
4. 混合回滚(默认,保留修改但不暂存)
bash
# 回滚到指定提交,修改保留在工作区
git reset --mixed <commit-hash>
# 或者简写
git reset <commit-hash>
5. 硬回滚(彻底删除修改)
bash
# 完全回滚到指定提交,丢弃所有之后的修改
git reset --hard <commit-hash>
6. 回滚到特定提交的示例
bash
# 先查看提交历史找到目标提交
git log --oneline
# 假设要回滚到提交 22490b9
git reset --hard 22490b9
# 或者回滚到前3个提交
git reset --hard HEAD~3
7. 使用 revert(推荐用于已推送的提交)
bash
# 创建一个新的提交来撤销之前的提交
git revert <commit-hash>
🚨 重要提醒
硬回滚前先备份
bash
# 先创建备份分支
git branch backup-branch
# 或者保存当前状态
git stash
如果已经推送到远程
bash
# 硬回滚后强制推送(谨慎使用!)
git push --force-with-lease
# 或者使用 revert 更安全
git revert <commit-hash>
git push
📋 推荐工作流程
-
先确认当前状态
bashgit status git log --oneline -10 -
创建备份
bashgit branch backup-before-rollback -
执行回滚
bashgit reset --hard <目标提交hash>
你想回滚到哪个具体的提交?可以先运行 git log --oneline 查看提交历史。