git 指定版本回退、临时保存 等操作

查看近20条提交记录

复制代码
git log --oneline -20

场景一:本地回退,不影响远端(最安全)

bash 复制代码
# 只是想本地代码回上一次提交后
git reset --hard HEAD~1
# 等价于:
git reset --hard 88c8975

注意:--hard 会丢弃未提交的修改

场景二:本地 + 远端都回退(你是唯一开发 / 已确认)

bash 复制代码
git reset --hard 88c8975
git push -f origin master

注意: 6dda5f4 会在远端历史中被"抹掉",如果别人已经拉了 6dda5f4,会造成历史冲突

场景三:不改历史,用"反向提交"撤销(最规范)

bash 复制代码
git revert 6d308ce

结果:新增一个 commit,撤销 6dda5f4 的所有修改

日志最新的那条会变成类似:xxxxx Revert

场景四:改动要保留,但不想现在提交

bash 复制代码
git stash
# 以后想恢复:
git stash pop

"防翻车"小技巧(很实用),回退前先打个 tag

tag = 给某个提交打一个"书签 / 保险点",等价于在 Git 历史里说:"我给 6d308ce 这个状态存个档"

bash 复制代码
git tag backup-6dda5f4
# 万一后悔了:
git reset --hard backup-6dda5f4

给你一套「不翻车标准流程」(建议你以后照抄)

bash 复制代码
# 1. 看状态
git status

# 2. 如果有改动,先存
git stash

# 3. 打保险 tag
git tag backup-before-reset

# 4. 回退
git reset --hard HEAD~1

恢复方案:

bash 复制代码
# 恢复回退点
git reset --hard backup-before-reset

# 恢复改动
git stash pop

总结:

reset = 改历史(危险)
revert = 不改历史(安全)
tag = 后悔药
stash = 临时抽屉

相关推荐
全栈陈序员5 小时前
Git】从入门到精通(八)—— git log:查看提交历史
大数据·git·elasticsearch
7177779 小时前
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
全栈陈序员2 天前
【Git】从入门到精通(六)—— git commit:提交到版本库
大数据·git·elasticsearch