Squash commits already pushed to remote
Posted: | Updated: | Tags: git tilSquash commits already pushed to GitHub
Here I squash the last N commits by rebasing and force pushing to GitHub or another remote while avoiding this helpful but unwanted error.
To https://github.com/LameLemon/pepe-is-the-man.git
! [rejected] master -> master (non-fast-forward)
error: failed to push some refs to 'https://github.com/LameLemon/pepe-is-the-man.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.
First, through interactive rebasing set the HEAD back to the number of commits you want to squash. If you wish to include the root commit replace HEAD~3
with --root
.
git rebase -i HEAD~3
In the text editor pick on commit to go with and squash the others.
pick 2871a3f adding the dankest pepe
squash ba1834f adding the second dankest pepe
squash 13ed324 adding the third dankest pepe
# Rebase 13ed324..2871a3f onto 9482e8a
#
# Commands:
# p, pick = use commit
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
#
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
#
Save and exit and on the next text file comment (#) everything except what you want the new commit message to be. Then save and exit again. Now the commits have been squashed.
Now force push the changes to the desired branch.
git push origin +master
From GitReady and StackOverflow.