“Merge” Last Two Commits
Have you ever wanted to merge your last two commits, maybe because you forgot to commit something in the first one, but you don’t know where to start? Well, read this article!
We have all been there, you commit some super-important changes you made, but suddenly realize that you forgot to commit something crucial.
Now you’re worried that your history will not be as clean as it was before! If only there was a way to merge your two commits together…
Well, luckily there is such a way, and is also quite simple:
How to merge the last two commits
git rebase --interactive HEAD~2.
Then, from the interactive interface that’s presented you (e.g. nano) type:
pick b76d157 commit message # penultimate commit hash
squash a931ac7 other commit message # last commit hash
# Rebase df23917..a931ac7 onto df23917
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# # If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
And now you will be prompted to another interactive interface in which the two commits messages are presented, and you’re free to edit them as you want (keep both, only the one you like the most, write a completely new one).
What if the two commits were already pushed?
In this case, just use
git push --force, but remember that this could be a risky operation depending on the situation, so use it carefully.
What if the commits I wanted to merge were three, or four, or more?
Nothing easier, just replace
HEAD~2, which means two commits behind HEAD, use
HEAD~3 or whatever number of commits you want, and then squash all the commits you want.
Example with three commits:
pick f7f3f6d Change my name a bit
squash 310154e Update README formatting and add blame
squash a5f4a0d Add cat-file