Converting multiple commits into single commit

Jay (Vijayasimha BR)
3 min readDec 12, 2024

--

A young Indian woman, wearing crop tops and shorts, surround by squashed exploding tomatoes, digital paint, digital art

In this quick post, I tell how, I go about merging or squashing multiple commits into a single commit.

Now, before I begin, why do this at all?

commit history is a good thing. we can track changes to the most minute level. However, when working in a team or an open-source project, it might best to show only the major changes as part of the commit. Occasionally, it might be a directive from the project owner, like a team lead or an organization guideline for code pushing as part of pull requests.

Now, first up, image I am working on a project. I have an empty, new project here.

alright then. Now, I will do a bunch of commits to simulate a situation of multiple commits.

and that looks like this on github as well.

Now, there are many ways to merge things. But, this is what I ended up liking, from this stack overflow post.

git reset --soft HEAD~5
git commit -m "new commit message"
git push -f

Note, the number 5 in the first step. I want to covert the last 5 commits into a single commit.

Note, again. If you make a mistake with the HEAD count, just do a

git pull

till you get the exact commit where you want to go to and repeat the commands.

Now, remember, you cannot just do a ‘git push’. you will get this.

PS D:\codedec2024ow\gitsquashpractice1> git push
To https://github.com/Jay-study-nildana/gitsquashpractice1.git
! [rejected] main -> main (non-fast-forward)
error: failed to push some refs to 'https://github.com/Jay-study-nildana/gitsquashpractice1.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. If you want to integrate the remote changes,
hint: use 'git pull' before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
PS D:\codedec2024ow\gitsquashpractice1>

So, I do a force push, kind of like Jedi Knights or Sith Lords.

and on GitHub.

So, there you go. easily said and easily done.

I work as a coding tutor. You can hire me on Upwork, Fiverr and Codementor. You can also book a session on calendly, and visit my website. Also, video tutorials on my YouTube Channel.

--

--

No responses yet