How to Squash Commits That Are Already Pushed in Git
This article outlines the process of squashing commits that we have already pushed to the remote repository. We squash commits into one to reduce clutter in our repository.
To squash commits, we run a git rebase
in the interactive mode.
Squash Commits That Are Already Pushed in Git
For easier context, we will simulate a scenario where we need to squash a few commits in one after pushing changes.
First, we will push our current changes to the remote repository.
$ git push origin Dev2.1
This command will push all changes to our remote branch Dev2.1
.
We can run the git rebase
command up to the 5th commit.
$ git rebase -i HEAD~5
Output:
To squash our commits, we will replace pick
with squash
at the beginning of the commits and finish the rebase.
We can run the git log
command to see our commit history.
Attempting a push will result in an error, as shown below.
The error is self-explanatory; we will not dwell much on that.
We need to force a push, not with the --force
flag but as shown below.
$ git push origin +Dev2.1
Output:
Let’s take a quick peep at the remote repo on GitHub.
We use the +
before the refspec
to force a push, in our case, to the Dev2.1
branch.
In conclusion, after squashing commits that you have already pushed to the remote, a normal git push
will not do you any good.
You will be stuck in an annoying loop where Git requires you to pull before pushing. Adding the +
before your branch in the git push origin
command solves the problem.
John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.
LinkedIn