Git的回滚方法

回滚到之前的提交有几种方法,具体取决于你的需求:

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

📋 推荐工作流程

  1. 先确认当前状态

    bash 复制代码
    git status
    git log --oneline -10
  2. 创建备份

    bash 复制代码
    git branch backup-before-rollback
  3. 执行回滚

    bash 复制代码
    git reset --hard <目标提交hash>

你想回滚到哪个具体的提交?可以先运行 git log --oneline 查看提交历史。

相关推荐
暮云星影5 小时前
git版本发布
git·gitee·github·gitea
独隅6 小时前
VS Code Git 工作树多分支并行开发实战评测
git
暮云星影11 小时前
git仓库分支管理
git·gitee·github·gitea
互联网中的一颗神经元1 天前
ZZ — Git 速查表
大数据·git·elasticsearch
早安试言1 天前
git使用
git
燐妤1 天前
梦绘片场 ProjectDream故事总纲场景剧本篇:从项目到成片的 AI 漫剧工作台
人工智能·git·ai·项目开发
JackieDYH2 天前
Git 与 GitHub 新电脑配置指南(从零开始)
git·github·工具·使用教程
Jeanyia2 天前
GitLab 配套 Git 常用命令
git·gitlab
10mAh2 天前
【Git】误删分支、reset --hard 后提交丢了怎么办?——reflog、fsck 与安全恢复实战
数据库·git·安全·回归
Lydro2 天前
CentOS 7 安装高版本git
git·centos 7