How to squash commits

darkmavis1980

Alessio Michelini

Posted on August 19, 2021

How to squash commits

When working with Git one important rule is to try to keep your commit history clean, avoiding to write pointless commit message such as "WIP", "TODO", etc...
But sometimes people can do honest mistakes, or they can code away, commit many times with small changes, and then perhaps you want to cleanup your commit history and group your changes under one commit.

Using the reset command

One way to do it is by resetting your commit history, so for example you have two commits, and you want to squash them in one, you can do this:

# Reset the history reverting back to the past 2 commits
git reset --mixed HEAD~2
Enter fullscreen mode Exit fullscreen mode

Now you will see that the code you changed in the past two commits is again ready to be commited again.

# Stage all the files
git add -A
# Commit the staged files
git commit -m "Your message"
Enter fullscreen mode Exit fullscreen mode

Now to rewrite the history on the remote, you will have push with the --force flag to apply those changes to the remote.

git push --force origin <YOUR-BRANCH-NAME>
Enter fullscreen mode Exit fullscreen mode

And now your history is clean as nothing ever happened :-)

Using the rebase command

Another way to do it is by using the rebase strategy:

# this lets you interactively select commits
git rebase -i HEAD~2
Enter fullscreen mode Exit fullscreen mode

Then select the commits you want to squash by setting s instead of pick, after that save with whatever editor your are using, and edit the commit message.

And as before you will have to override history with this:

git push --force origin <YOUR-BRANCH-NAME>
Enter fullscreen mode Exit fullscreen mode

This is a much quicker way and it has the advantage of letting you pick which commmits to squash, but the disadvantage is that using rebase could be problematic if you don't know exactly what are you doing, and I would recommend to read this link.

💖 💪 🙅 🚩
darkmavis1980
Alessio Michelini

Posted on August 19, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

How to squash commits
github How to squash commits

August 19, 2021