撤消 git 提交

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12704568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 07:34:50  来源:igfitidea点击:

Undo a git commit

gitgit-commit

提问by edwardmlyte

Can you undo a past commit, that has long been merged into your git repository, via a git command? Or do you have to manually undo all the changes made in that commit?

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

回答by sehe

You can always just revert the changes from a single commit by doing:

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

git revert <commit-id>

note that this creates a newcommit, undoing just those changes

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

E.g. git log --oneline

例如 git log --oneline

d806fc9 two
18cdfa2 bye
62c332e hello
c7811ee initial

Say I want to revert changes in commit 18cdfa2:

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

git revert 18cdfa2

We now have: git log -1 -p

我们现在有: 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

回答by automaticAllDramatic

You can always do git revert <commit-hash>to undo a git commit. However, this in most cases is not helpful because it creates a new commit adding to your git reflog.

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

What I usually do when I have to step back is reset my branch to an earlier stage. To do this, do a git reflog and look for the HEAD position you want to move to.

当我不得不后退时,我通常会做的是将我的分支重置到较早的阶段。为此,请执行 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

Now, say I want to move to commit hash 2a59955and undo all the changes in 8d386b8. I would do:

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

Update: git reset --soft HEAD@{1} 

This will reset my branch to the initial state. Doing this will not only undo all the changes, but also stops tracking all the files that you might have added in this commit. By all means, this is the most efficient way to undo all the changes in a single commit.

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

This will undo all your changes. There is a hard reset meant to go back in time (at least from a git point of view). Use --hardin place of --softfor this

这将撤消您的所有更改。有一个硬重置意味着回到过去(至少从 git 的角度来看)。为此使用--hard代替--soft