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 查看提交历史。

相关推荐
Unity粉末状在校生5 小时前
Git解决fatal: Could not read from remote repository.的问题
git
少年攻城狮6 小时前
Obsidian系列---【如何使用obsidian同步到git?】
git
do better myself8 小时前
网站源码如何部署和加入GIT仓库的
git
爱学英语的程序员11 小时前
Git 提交 LF will be replaced by CRLF the next time Git touches it 报错
git
qq_3391911411 小时前
服务器git pull每次都要输入密码,linux 设置git登录,linux设置git只输入一次账户密码
git
一颗小行星!17 小时前
快速理解 Git submodule
git
A-Jie-Y20 小时前
Git基础-核心概念与常用命令
git
夜珀20 小时前
Git基础修炼手册:在AtomGit上玩转版本控制
git
golang学习记20 小时前
Zed IDE官宣新招:Git Graph 正式支持!
ide·git
要记得喝水21 小时前
适用于 Git Bash 的脚本,批量提交和推送多个仓库的修改
git·elasticsearch·bash