0

How do I combine 2 commits into one when the previous one was already pushed?

Step 1

git add file.txt git commit git push 

Step 2

git add file.txt git commit 
3
  • 3
    Be careful with this if you have other developers who may have pulled the published commit. Best practice is not to alter commits that have already been pushed. Doing so will “rewrite history” and require extra work for others working on the project. Commented Oct 11, 2018 at 23:50
  • Possible duplicate of how to combine commits and push to the remote Commented Oct 12, 2018 at 1:14
  • stackoverflow.com/search?q=%5Bgit%5D+combine+commits Commented Oct 12, 2018 at 1:14

4 Answers 4

2

You can do it using rebasing. Squash the last two commits with git rebase -i HEAD~2. Then do a force push with git push --force**.

** Generally you should prefer --force-with-lease over --force. If someone else were to push to the branch you are pushing --force would overwrite their changes. --force-with-lease would only force push if no one else has pushed to that branch.

Sign up to request clarification or add additional context in comments.

Comments

1
git add file.txt git commit --amend git push --force 

The usual warnings about --force apply.

Comments

1

Try:

git reset --soft HEAD~2 git commit -m "Your new message" git push --force 

What this does:

  1. Reset your current branch (moves HEAD) to antepenultimate commit (the one before the penultimate, represented by HEAD~2) but leaves the index and the working tree.
  2. This allows to re-stage these changes and commit them in a brand new commit.
  3. --force allows you to push this new commit and force an override.

NOTE

As others have commented on your original question, beware that --force will most likely annoy other people that have already pulled the previous version of this branch. You could "squash" these changes into a new branch and publish it separately:

git reset --soft HEAD~2 git checkout -b my-new-clean-branch git commit -m "Your new message" git push -u origin HEAD 

This way you don't need to --force anything.

3 Comments

You should probably include an explanation about the effects this will have on other developers who may have pulled the branch.
Squashing into a new branch just duplicates the changes in two different commits. The OP and other visitors should just be aware that a force push can cause problems for others who pulled the branch. Squashing should only be used when no one else is on the same branch
@Code-Apprentice The idea here is that you could "abandon" the previous branch and start a new independent history. Also, you are truly committing the combined changes of 2 commits into a single one, which is what was asked how to achieve.
0

Follow these commands in order.

git add .

git commit --amend

git push origin <branch> -f

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.