KingKongFrog
KingKongFrog

Reputation: 14419

Combine 2 git commits when previous was pushed

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 

Upvotes: 0

Views: 267

Answers (4)

Aakash Pahuja
Aakash Pahuja

Reputation: 480

Follow these commands in order.

git add .

git commit --amend

git push origin <branch> -f

Upvotes: 0

Fernando Espinosa
Fernando Espinosa

Reputation: 4855

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.

Upvotes: 1

user3723506
user3723506

Reputation:

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.

Upvotes: 2

Adam Millerchip
Adam Millerchip

Reputation: 23137

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

The usual warnings about --force apply.

Upvotes: 1

Related Questions