Git Revert Pushed Commit如何撤消上次提交
在这篇文章中,我将展示如何使用命令行上的 git 恢复编码项目中的错误更改(提交)。
我为什么要这么做?
在我的论文中,我正在开发一个项目,该项目在一个环境中开发,然后在另一个由多个虚拟机组成的环境中进行测试。因此,我所做的每个重要更改都可能对项目的功能产生重大影响。有时,我所做的更改可能不会达到预期的结果。因此,我必须查看这些更改,并分析项目在最后一次提交前后的行为。
您如何查看最后一次提交?
要测试特定的提交,你需要哈希值。要获取哈希值,你可以运行git log
,然后会得到以下输出:
root@debian:/home/debian/test-project# git log
commit <last commit hash>
Author: Isabel Costa <example@email.com>
Date: Sun Feb 4 21:57:40 2018 +0000
<commit message>
commit <before last commit hash>
Author: Isabel Costa <example@email.com>
Date: Sun Feb 4 21:42:26 2018 +0000
<commit message>
(...)
您还可以运行git log --oneline
以简化输出:
root@debian:/home/debian/test-project# git log --oneline
<last commit hash> <commit message>
cdb76bf Added another feature
d425161 Added one feature
(...)
<before last commit hash>
要测试您认为具有最新工作版本的特定提交(例如:),您可以键入以下内容:
git checkout <commit hash>
这将使工作存储库与此精确提交的状态相匹配。
完成此操作后,您将获得以下输出:
root@debian:/home/debian/test-project# git checkout <commit hash>
Note: checking out '<commit hash>'.
You are in 'detached HEAD' state. You can look around, make experimental changes
and commit them, and you can discard any commits you make in this state without
impacting any branches by performing another checkout.
If you want to create a new branch to retain commits you create, you may do so
(now or later) by using -b with the checkout command again. Example:
git checkout -b new_branch_name
HEAD is now at <commit hash>... <commit message>
分析特定的提交之后,如果您决定停留在该提交状态,则可以撤消最后一次提交。
如何撤消此提交?
如果您希望撤消/恢复最后一次提交,您可以使用从命令中获取的提交哈希执行以下操作git log
:
git revert <commit hash>
此命令将创建一个新的提交,并在消息开头添加“Revert”字样。之后,如果您检查存储库状态,您会注意到 HEAD 已从之前测试的提交处分离。
root@debian:/home/debian/test-project# git status
HEAD detached at 69d885e
(...)
您不想看到此消息,因此要修复此问题并将 HEAD 重新附加到您的工作存储库,您应该检出您正在处理的分支:
git checkout <current branch>
在撰写这篇文章的过程中,我发现了 Atlassian 的这个教程——Undoing Commits and Changes ,它很好地描述了这个问题。
概括
-
如果您想测试前一次提交,只需执行
git checkout <test commit hash>
;然后您就可以测试项目的最后一个工作版本。 -
如果您想恢复最后一次提交,只需执行
git revert <unwanted commit hash>
;然后您可以推送这个新的提交,这将撤消您之前的提交。 -
要修复脱落的头部,请执行以下操作
git checkout <current branch>
。
您可以在Twitter、LinkedIn、Github、Medium和我的个人网站上找到我。
文章来源:https://dev.to/isabelcmdcosta/how-to-undo-the-last-commit--31mg