前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >git commit回滚

git commit回滚

作者头像
艳龙
发布2021-12-16 17:29:59
8.2K0
发布2021-12-16 17:29:59
举报
文章被收录于专栏:yanlongli_艳龙yanlongli_艳龙

从svn 迁移到 git,已经有很长时间。git 的基本命令已经可以说是熟练的掌握,能够满足日常的开发。想了解常用git命令可以查看: 常用git命令

但是也有一些不常用,但在关键时刻又非常有用的命令,这里就介绍一种:撤销已经提交的commit

1. 应用场景 :

撤销已经提交的commit

2. 解决方案:

  1. 使用 git reset --hard HEAD^
  2. 使用 git rebase -i HEAD~n

下面分别介绍下这两个方案有什么不同,和他们的使用场景 。

2.1 git reset --hard 丢弃最新的提交

代码提交后,需求发生变化导致之前提交的已经不合适,或者 代码提交后发现有严重bug,需要回滚可是使用这个命令:

git reset --hard HEAD^

tips:

代码语言:javascript
复制
1,HEAD^   表示 最新提交HEAD位置往回数一个提交, 几个 ^  就往回数几个提交;

2,HEAD~n  表示 新提交HEAD位置往回数n个提交

可以发现,reset 命令只能回滚最新的提交。

如果最后一次commit需要保留,而只想回滚之前的某次commit,reset命令可能就无法满足了。(这个场景我第一次遇到的时候很是抓瞎)

2.2 git rebase -i 丢弃指定提交

针对想撤销中间某次commit的情况,可以使用如下的命令:

git rebase -i HEAD~2

tips:

代码语言:javascript
复制
1, `rebase -i`是 `rebase --interactive` 的缩写;
2,  `git rebase -i` 不仅可以删除commit, 还可以修改commit。 具体的可以查看rebase 中提示的参数

输入git rebase -i HEAD~2命令后,会出现一个编辑页面如下:

代码语言:javascript
复制
$ git rebase -i HEAD~2

drop e47fa58 提交11
pick 338955c 提交12

# Rebase 7f83da3..338955c onto 7f83da3 (2 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
# f, fixup <commit> = like "squash", but discard this commit's log message
# x, exec <command> = run command (the rest of the line) using shell
# b, break = stop here (continue rebase later with 'git rebase --continue')
# d, drop <commit> = remove commit
# l, label <label> = label current HEAD with a name
# t, reset <label> = reset HEAD to a label
# m, merge [-C <commit> | -c <commit>] <label> [# <oneline>]
# .       create a merge commit using the original merge commit's
# .       message (or the oneline, if no original merge commit was
# .       specified). Use -c <commit> to reword the commit message.
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out
~      

编辑界面能够执行的操作,都有罗列出来:

代码语言:javascript
复制
`edit: 使用本次提交,在rebase到这次提交时候,会暂停下来等待修正`
`pick:使用本次提交,不操作修改`
`drop:删除这次提交`
`...`

这里的目标是删除倒数第二个提交,所以将倒数第二个提交前面修改为drop, 然后退出编辑界面就可以了。

再通过 git log 查看提交历史的时候,就会发现e47fa58 的提交记录已经不见了。

总结:

  1. 回滚最新的提交 :git resetgit rebase 命令都可以
  2. 回滚中间某次提交: git rebase 可以, git reset 不可以
  3. 如果提交已经同步到远程仓库,需要使用git push origin -f branch(分支名) 来将回滚也同步到远程仓库(master 分支谨慎使用 -f)
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/11/7 下,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 应用场景 :
  • 2. 解决方案:
  • 2.1 git reset --hard 丢弃最新的提交
  • 2.2 git rebase -i 丢弃指定提交
  • 总结:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档