如何撤销 Git 的最后一次提交

DevTools

如何撤消上次提交

在这篇文章中,我将展示如何在命令行上使用 git 恢复编码项目中的错误更改(提交)。

我为什么要这样做?

在我的论文中,我正在做一个项目,我在一个环境中开发,然后在另一个由多个虚拟机组成的环境中进行测试。因此,我所做的每一项重要更改都可能对项目的功能产生重大影响。有时,我所做的改变可能不会达到我预期的结果。然后我必须查看更改并分析项目在上次提交前后的行为。

DevTools

如何撤销最后一次提交

在本文中,我将显示如何在命令行中使用 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我的个人网站 上找我。

git
本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://code.likeagirl.io/how-to-undo-th...

译文地址:https://learnku.com/devtools/t/71279

本文为协同翻译文章,如您发现瑕疵请点击「改进」按钮提交优化建议
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!