Today in this blog I’ll explain how to squash related commits into one commit. Before how let’s see what we mean by squashing git commit. As the name suggests it means combining multiple commits.
Let’s suppose, there are multiple pushed commits for a single issue or a feature. Then we can squash those multiple commits into one for better management.
For example I’ll show how to squash two commits into one. I have created a demo repo. I have done two commits “first commit” and “second commit” as you can see below,
Now the goal is to combine these two commits into one commit.
To do this run
git rebase -i HEAD~2 here we have used 2 because we are squashing two commits. You should use the number of commits you want to squash. It can be any number. After running this it will open up editor, there you will see the last two commits that you are wanting to squash as shown below,
Now change the “pick” to “squash” in front of all the commits that you want to squash so in here I’ll change second one to “squash” as shown below,
After that we will save it and it will open another file in the editor to manage the commit message as shown here,
Now you can remove the previous messages and add some new message,
After that you will get success message on the terminal,
Now we have to push it forcefully, to do that run
git push -f origin sanjay
As you can see below the previous two commits have been replaced with the new commit,
Thanks for reading. Feel free to comment if you face any issue.