简体   繁体   English

撤消git提交

[英]Undo a git commit

Can you undo a past commit, that has long been merged into your git repository, via a git command? 您是否可以通过git命令撤消过去的提交,该提交早已合并到您的git存储库中? Or do you have to manually undo all the changes made in that commit? 或者您是否必须手动撤消该提交中所做的所有更改?

You can always just revert the changes from a single commit by doing: 您始终可以通过执行以下操作从单个提交中还原更改:

git revert <commit-id>

note that this creates a new commit, undoing just those changes 请注意,这会创建一个提交,只撤消这些更改

Eg 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

You can always do git revert <commit-hash> to undo a git commit. 您可以随时执行git revert <commit-hash>来撤消git提交。 However, this in most cases is not helpful because it creates a new commit adding to your git reflog. 但是,这在大多数情况下没有帮助,因为它会创建一个新的提交添加到您的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 2a59955 and undo all the changes in 8d386b8 . 现在,说我想要移动到提交哈希2a59955和撤消所有更改8d386b8 I would do: 我会做:

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). 有一个硬重置意味着可以追溯到时间(至少从git的角度来看)。 Use --hard in place of --soft for this 使用--hard代替--soft为此

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM