跳至主要内容

更改提交信息

如果提交信息包含模糊、不正确或敏感信息,您可以在本地修正它并将带有新信息的新提交推送到 GitHub。您也可以更改提交信息以添加缺失的内容。

更改最近一次提交信息

您可以使用 git commit --amend 命令更改最近一次提交的信息。

在 Git 中,提交信息的文本是提交本身的一部分。更改提交信息会导致提交 ID(即为提交命名的 SHA1 校验和)发生变化。实际上,您是在创建一个取代旧提交的新提交。

提交尚未在线推送

如果该提交仅存在于本地仓库且尚未推送到 GitHub.com,您可以使用 git commit --amend 命令来修改提交信息。

  1. 在命令行中,切换到包含您想要修改的提交的仓库目录。
  2. 输入 git commit --amend 并按 Enter
  3. 在文本编辑器中编辑提交信息,然后保存提交。

下次推送时,新提交和信息将显示在 GitHub.com 上。

提示

您可以通过修改 core.editor 设置来更改 Git 的默认文本编辑器。更多信息,请参阅 Git 手册中的 基本客户端配置

修订旧的或多个提交信息

如果您已经将该提交推送到 GitHub.com,则需要使用强制推送(force push)来提交已修改信息的提交。

警告

我们强烈不建议使用强制推送,因为它会更改仓库的历史记录。若强制推送,已经克隆您仓库的用户必须手动修复本地历史。更多信息,请参阅 Git 手册中的 从上游 rebase 恢复

更改最近一次已推送提交的信息

  1. 按照 上面步骤 修改提交信息。

  2. 使用 push --force-with-lease 命令强制推送,以覆盖旧的提交。

    git push --force-with-lease origin EXAMPLE-BRANCH
    

更改旧的或多个提交的信息

如果需要修改多个提交或较早提交的信息,可以使用交互式 rebase,然后强制推送以更改提交历史。

  1. 在命令行中,切换到包含您想要修改的提交的仓库目录。

  2. 使用 git rebase -i HEAD~n 命令,在默认文本编辑器中显示最近 n 个提交的列表。

    # Displays a list of the last 3 commits on the current branch
    $ git rebase -i HEAD~3
    

    该列表将类似如下:

    pick e499d89 Delete CNAME
    pick 0c39034 Better README
    pick f7fde4a Change the commit message but push the same commit.
    
    # Rebase 9fdb3bd..f7fde4a onto 9fdb3bd
    #
    # Commands:
    # p, pick = use commit
    # r, reword = use commit, but edit the commit message
    # e, edit = use commit, but stop for amending
    # s, squash = use commit, but meld into previous commit
    # f, fixup = like "squash", but discard this commit's log message
    # x, exec = run command (the rest of the line) using shell
    #
    # These lines can be re-ordered; they are executed from top to bottom.
    #
    # If you remove a line here THAT COMMIT WILL BE LOST.
    #
    # However, if you remove everything, the rebase will be aborted.
    #
    # Note that empty commits are commented out
    
  3. 在每个想要修改的提交信息前,将 pick 替换为 reword

    pick e499d89 Delete CNAME
    reword 0c39034 Better README
    reword f7fde4a Change the commit message but push the same commit.
    
  4. 保存并关闭提交列表文件。

  5. 在每个生成的提交文件中,输入新的提交信息,保存文件并关闭。

  6. 准备好将更改推送到 GitHub 时,使用 push --force 命令强制推送,以覆盖旧的提交。

    git push --force origin EXAMPLE-BRANCH
    

有关交互式 rebase 的更多信息,请参阅 Git 手册中的 交互模式

注意

如前所述,修改提交信息会生成一个拥有新 ID 的新提交。然而,在这种情况下,所有位于已修改提交之后的提交也会获得新的 ID,因为每个提交都包含其父提交的 ID。

警告

如果您在提交信息中包含了敏感信息,即使强制推送已修改的提交,也可能无法从 GitHub 上彻底删除原始提交。旧的提交不会出现在后续的克隆中,但它可能仍被 GitHub 缓存并可通过提交 ID 访问。您必须通过 GitHub 支持门户 提交旧的提交 ID,请求将其从远程仓库中彻底清除。

延伸阅读

© . This site is unofficial and not affiliated with GitHub, Inc.