How to edit, delete existing commits in Git

How to To fix premature commits that often occur during normal development?

有时,开发粗心,漏写一些不是很重要的东东(比如typo),如果再因此增加一个commit,既会让 Git history 变得混乱,又没有必要。

  1. 找到要修改的commit,在下面的命令中输入其commit ID
$ git rebase -i commitID
  1. 在类似下面的列表中,将要操作的commit前面的关键字修改为edit,保存,关闭编辑器。
pick 58dec2a Create the about page
edit 6ac8a9f Begin creating bio pages
pick 51c958c Add link to about section in home page
  1. 然后进行自己想要进行的操作,并 git addstaging area

  2. $ git commit --amend,在编辑器中不修改已有内容,直接关闭。

  3. 此时,按照屏幕提示,就可以进行 git rebase --continue的操作,完成整个 rebase 过程了。

这样,就达到了修改内容但不修改历史的目的。

How to drop a commit?

有时有些commit是多余的,如何删除?

  1. 找到要修改的commit,在下面的命令中输入其commit ID
$ git rebase -i commitID
  1. 在类似下面的列表中,将要操作的commit前面的关键字修改为drop,保存,关闭编辑器。
pick 58dec2a Create the about page
drop 6ac8a9f Begin creating bio pages
pick 51c958c Add link to about section in home page
  1. 此时,按照屏幕提示,就可以进行 git rebase --continue的操作,完成整个 rebase 过程了。

How to overwrite the remote repo history?

如果进行了上述操作,git status会提示本地与远程有差异,需要git pull,此时如果pull,前面就白干了。需要强行push到remote。

$ git push --force origin example-branch

当然,如果是多人协作项目,这个方法是不推荐的。

FYI

docs.github.com/en/pull-requests/c...

Others

git version 2.37.2

本作品采用《CC 协议》,转载必须注明作者和本文链接
日拱一卒
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
92
粉丝
87
喜欢
152
收藏
121
排名:72
访问:11.3 万
私信
所有博文
社区赞助商