git 将多个 commit 合并成一个 commit 提交

  • 2020-11-18
  • 浏览 (1554)

在git分支上有多次git commit或多次git push,想将多次提交的commit合并成一个commit,方便代码管理。

例如将最近四次提交的commit合并成一个。操作步骤:

1、查看提交历史记录

git log

2、回退到第5个提交,将后面4次提交的内容变为未提交状态

git reset commitID(第五个commitID)  //git reset 等同于git reset --mixed

3、提交修改内容

git add .
git commit -m "将前四个commit合并成一个"

4、将代码提交到远程分支

git push
To https://xxxx/Test.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://xxxx/Test.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

5、强推

无法提交,因为本地没有远端的4个commit,导致不一致无法推送,因此需要强行推上去。强推应该注意的是确保在做这个操作的时候没有其他人往这个分支上提交代码,否则会造成将他人的代码覆盖。

另外只是在本地分支多次git commit,并没有多次git push则不需要强推,即git push不会发生rejected的情况。如果发生了,就是有其他人往这个分支上提交了代码。

git push -f
0  赞