由于一些糟糕的选择,我的本地Git存储库目前比原始库提前了五次提交,并且状态不佳。我想摆脱所有这些承诺,重新开始。

很明显,删除我的工作目录并重新克隆就可以了,但再次从GitHub下载所有内容似乎太过了,而且没有很好地利用我的时间。

也许git-restore是我需要的,但我不想在源代码之前提交10次(甚至6次),即使它确实将代码本身恢复到正确的状态。我只想假装最后半小时从未发生过。

有一个简单的命令可以做到这一点吗?这似乎是一个明显的用例,但我找不到任何例子。


请注意,这个问题专门针对提交,而不是:

未跟踪的文件未分级更改已分段但未提交的更改


当前回答

您可以考虑使用带有drop命令的交互式rebase

比如说最后三次犯罪。。。

git rebase -i HEAD~3

交换拾取命令

pick <hash1> Commit message 1
pick <hash2> Commit message 2
pick <hash3> Commit message 3

用于放置命令

drop <hash1> Commit message 1
drop <hash2> Commit message 2
drop <hash3> Commit message 3

其他回答

Try:

git reset --hard <the sha1 hash>

将你的头重置到你想去的任何地方。使用gitk查看你想去哪一个提交。你也可以在gitk内重置。

我有一种情况,我想删除一个未被推送的提交,但该提交在另一个提交之前。为此,我使用了以下命令

git rebase-i HEAD~2->它将对最后两次提交进行重新基化

我使用“drop”作为我想要删除的提交签名。

您可以使用此git命令

git reset --hard origin/<branch_name>

在回答之前,让我们添加一些背景,解释一下这个HEAD是什么。因为下面的一些选项会导致头部分离

首先,什么是头部?

HEAD只是对当前分支上当前提交(最新)的引用。在任何给定时间只能有一个HEAD。(不包括git工作树)

HEAD的内容存储在.git/HEAD中,它包含当前提交的40字节SHA-1。


分离式封头

如果您不在最近一次提交中,这意味着HEAD指向历史上的先前提交,它称为分离的HEAD。

在命令行上,它看起来像-SHA-1而不是分支名称,因为HEAD没有指向当前分支的末端

关于如何从分离的HEAD恢复的几个选项:


git校验

git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits t go back

这将签出指向所需提交的新分支。此命令将签出到给定的提交。此时,您可以创建一个分支并从此开始工作。

# Checkout a given commit. 
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>

# create a new branch forked to the given commit
git checkout -b <branch name>

数字刷新

您也可以始终使用reflog。git reflog将显示更新HEAD的任何更改,检查所需的reflog条目将将HEAD设置回该提交。

每次修改HEAD时,reflog中都会有一个新条目

git reflog
git checkout HEAD@{...}

这会让你回到你想要的承诺


git reset--hard<commit_id>

将你的头“移”回所需的位置。

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.

注:(自Git 2.7以来)您也可以使用git rebase--也可以不使用autostash。


git还原<sha-1>

“撤消”给定的提交或提交范围。重置命令将“撤消”给定提交中所做的任何更改。将提交带有撤销补丁的新提交,而原始提交也将保留在历史记录中。

# add new commit with the undo of the original one.
# the <sha-1> can be any commit(s) or commit range
git revert <sha-1>

此模式说明了哪个命令执行什么操作。正如您可以看到的那样,重置和签出修改HEAD。

删除最近的提交,而不破坏您所做的工作:

git reset—软HEAD~1

删除最近的提交并删除更改:

git重置--硬HEAD~1