切换到旧提交,同时保证当前修改不丢失

在 Git 中,可以通过以下几种方式切换到之前的提交,同时保留当前的提交(即不丢失工作进度):

1. 使用 git checkout 创建临时分离头指针(推荐用于查看)

bash 复制代码
git checkout <commit-hash>

这会让你进入"分离头指针"状态,你可以查看旧代码。要返回最新提交:

bash 复制代码
git checkout <原来的分支名>

2. 使用 git branch 创建新分支(最安全)

bash 复制代码
git branch temp-branch <commit-hash>  # 创建临时分支指向旧提交
git checkout temp-branch              # 切换到临时分支

这样你的原分支和新提交都完好保存,可以在临时分支上操作。

3. 使用 git stash 暂存当前修改(修改未提交)

bash 复制代码
git stash          # 保存当前工作
git checkout <commit-hash>  # 切换到旧提交
# 查看或操作后...
git checkout -     # 回到原分支
git stash pop      # 恢复暂存的修改

4. 使用 git reset --soft(可逆操作)

如果想在当前分支"回退"到旧提交但保留所有更改在暂存区:

bash 复制代码
git reset --soft <commit-hash>

之后可以用 git reset ORIG_HEAD 撤销这次回退。

注意事项:

  • 所有方法都不会丢弃提交,只要提交还在 reflog 中(默认保留90天)
  • 要永久丢弃提交需要使用 git reset --hard 或 git push -f(慎用)
  • 推荐优先使用创建新分支的方式,这是最安全的选择

可以通过 git reflog 查看所有历史操作记录,找回"丢失"的提交。

相关推荐
全栈陈序员7 小时前
Git】从入门到精通(八)—— git log:查看提交历史
大数据·git·elasticsearch
71777711 小时前
Git自建用什么工具比较好:Gitea、Forgejo、GitLab CE与Gitee的选型对比
git·gitlab·gitea
lsc_blog1 天前
年底还在招的岗位,先确认缺口和到岗要求
git·缓存·ci/cd·职场和发展·github
全栈陈序员1 天前
【Git】从入门到精通(十一)—— git reset 三种模式详解
git·elasticsearch
全栈陈序员2 天前
【Git】从入门到精通(十)—— 撤销与恢复:git checkout与git restore
运维·网络·数据库·git
全栈陈序员2 天前
【Git】从入门到精通(五)—— git add:将文件加入暂存区
大数据·git·elasticsearch
全栈陈序员2 天前
【Git】从入门到精通(七)—— git status:查看仓库状态
大数据·git·elasticsearch
莫晓燚2 天前
Ansible 13 个常用模块---企业实战
git·github
无言听风雨丶2 天前
Kubernetes GitOps 持续交付实战:用 Argo CD 让 Git 成为集群事实源
git·elasticsearch·kubernetes
全栈陈序员3 天前
【Git】从入门到精通(六)—— git commit:提交到版本库
大数据·git·elasticsearch