1. Learn center
  2. Software Development
  3. Guides
  4. Git tutorial
  5. 如何使用 Git
  6. 如何在 Git 中管理历史记录
  7. 移除以前的提交
Git

Project and code management together.

Try it free

移除以前的提交

请转至您之前下载的git-tutorial/tutorial3目录。

当您检查此存储库的历史记录时,它将如下所示:

Current history

我们将使用 git reset 命令来撤消前两次提交。

首先,打开sample.txt文件,并确认其内容如下所示:

Anyone can learn Git with this tutorial and Backlog
add: Register a change in an index
commit: Save the status of an index
pull: Obtain the content of the remote repository

使用重置命令来删除前两次提交,如下所示。

Delete the commit
$ git reset --hard HEAD~~
  HEAD is now at 326fc9f append description of the add command

sample.txt文件将不再包含最后两行 (即commit: Save the status of an indexpull: Obtain the content of the remote repository)。

使用 git log 命令来验证这些提交是否已经不在历史记录中。

$ git log
  commit 326fc9f70d022afdd31b0072dbbae003783d77ed
  Author: yourname <yourname@yourmail.com>
  Date:   Mon Jul 16 23:17:56 2022 +0900

      append description of the add command

  commit 48eec1ddf73a7fb508ef664efd6b3d873631742f
  Author: yourname <yourname@yourmail.com>
  Date:   Mon Jul 16 23:16:14 2022 +0900

      first commit

ORIG_HEAD 指向重置发生前的原始提交。当您不小心发出重置时,这会派上用场。

您可以通过执行对 ORIG_HEAD 的重置来恢复以前的历史记录。

$ git reset --hard ORIG_HEAD
  HEAD is now at 0d4a808 append description of the pull command

Subscribe to our newsletter

Learn with Nulab to bring your best ideas to life