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 协议》,转载必须注明作者和本文链接
日拱一卒
未填写
文章
92
粉丝
87
喜欢
152
收藏
121
排名:73
访问:11.3 万
私信
所有博文
社区赞助商