撤消git提交

edw*_*yte 21 git git-commit

您是否可以通过git命令撤消过去的提交,该提交早已合并到您的git存储库中?或者您是否必须手动撤消该提交中所做的所有更改?

seh*_*ehe 33

您始终可以通过执行以下操作从单个提交中还原更改:

git revert <commit-id>
Run Code Online (Sandbox Code Playgroud)

请注意,这会创建一个提交,只撤消这些更改

例如 git log --oneline

d806fc9 two
18cdfa2 bye
62c332e hello
c7811ee initial
Run Code Online (Sandbox Code Playgroud)

假设我想恢复提交中的更改18cdfa2:

git revert 18cdfa2
Run Code Online (Sandbox Code Playgroud)

我们现在有: git log -1 -p

commit fb9d6627a71636503fc9a1eb4f725937c783ecee
Author: Seth <sehe@mint12.(none)>
Date:   Wed Oct 3 10:32:46 2012 +0200

    Revert "bye"

    This reverts commit 18cdfa27c964b66b624be1030250757b745d6866.

diff --git a/a b/a
index 0907563..3b18e51 100644
--- a/a
+++ b/a
@@ -1 +1 @@
-bye world
+hello world
Run Code Online (Sandbox Code Playgroud)


aut*_*tic 13

您可以随时git revert <commit-hash>撤消git提交.但是,这在大多数情况下没有帮助,因为它会创建一个新的提交添加到您的git reflog.

当我不得不退后时,我通常会做的是将我的分支重置为早期阶段.要执行此操作,请执行git reflog并查找要移动到的HEAD位置.

rizwan@dragonstone:~/myrepo$ git reflog -3
8d386b8 HEAD@{0}: commit: I did something I don't want
2a59955 HEAD@{1}: commit: Feedback from PR #792
1023102 HEAD@{2}: checkout: moving from one branch to another
Run Code Online (Sandbox Code Playgroud)

现在,假设我想提交哈希2a59955并撤消所有更改8d386b8.我会做:

Update: git reset --soft HEAD@{1} 
Run Code Online (Sandbox Code Playgroud)

这会将我的分支重置为初始状态.执行此操作不仅会撤消所有更改,还会停止跟踪您在此提交中可能添加的所有文件.无论如何,这是撤消单个提交中所有更改的最有效方法.

这将撤消所有更改.有一个硬重置意味着可以追溯到时间(至少从git的角度来看).使用--hard代替--soft

  • 柔软的!你使用SOFT!您使用该命令丢失了更改.我一直在寻找如何撤销一个承诺太多的提交(该死的,intellij)所以这是对下一个人的警告. (4认同)
  • 答案是否需要更新为SOFT?另外,请参阅http://stackoverflow.com/a/21778/509213以从不需要的HARD重置中恢复. (2认同)