git rebase -i命令修改commit历史

目录

修改commit历史的前提

修改历史的提交是可能有风险的,是否有风险取决于commit是否已经推送远程分支,未推送,无风险,如果已推送,就千万不要修改commit了。

修改commit历史,不是在原有commit结点上修改,而是用一个新的结点替换原来结点,所以,修改后commit id是不样的。

所以修改commit历史的前提是,提交未推送远程仓库!提交未推送远程仓库!提交未推送远程仓库!,重要的事情说三遍。

修改最近的一次提交

修改最近的一次提交非常简单,通过git commit --amend,该命令可以让我们修改提交的commit信息,也修改提交的内容。

修改提交的commit信息,可以直接运行该命令,然后在弹出的编辑框中修改提交信息保存即可。

修改提交的内容,可以先修改好内容,然后git add暂存区,再使用git commit --amend,填写commit信息保存即可。

修改更早的提交或修改多个提交

修改更早的提交或修改多个提交就需要用到git rebase -i parentCommitID,其机理是通过重新衍合parentCommitID之后的全部提交,所以该操作会改变parentCommitID结点之后所有提交的commit id。

通过rebase -i我们可以交互式的运行rebase,以达到修改更早的提交或修改多个提交。

运行这个命令会弹出一个文本编辑器,其中包含了提交列表和一些简单说明,形如:

pick f7f3f6d changed my name a bit
pick 310154e updated README formatting and added blame
pick a5f4a0d added cat-file

# Rebase 710f0f8..a5f4a0d onto 710f0f8
#
# Commands:
#  p, pick = use commit
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
#

你会发现提交列表的顺序与通过git log查看的命令是相反的,而且在每条提交前面都有一个pick,在说明中有提到,是选择该次提交,即不做修改,如果需要修改某个提交,就将对应记录(可是多个记录)的pick改为edit。保存,关闭文本编辑器后,回到命令行,会停在第一个标记为edit的提交前,eg:

$ git rebase -i HEAD~3
Stopped at 7482e0d... updated the gemspec to hopefully work better
You can amend the commit now, with

       git commit --amend

Once you’re satisfied with your changes, run

       git rebase --continue

根据提示,修改完成之后执行git commit --amend修改提交,然后执行git rebase --continue继续rebase。

所以rebase -i的流程如下:

  • git rebase -i parentCommitID
  • 在弹出的文本编辑器中,将要修改的commit的前方的pick改为edit,保存,关闭文本编辑器
  • 在命令行处于等待状态后,修改内容
  • 执行git commit --amend修改提交
  • 执行git rebase --continue继续rebase
  • 完成
    原文作者:苍枫露雨
    原文地址: https://www.cnblogs.com/chrischennx/p/6993734.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞