Git : Rebasing and Forced push

When is Rebasing needed ?

Has it ever happened that you pushed a lot of useless commits to the origin/master for fixing continuous integration tests or just to make minor changes, or you chose poor commit messages and want to edit them.

It just makes the commit history extremely untidy…!

How does forced push help?

It  is used to rewrite “history”. Too much eh…?
History referring here to the commits on the origin master,  it helps to change the commit history.

Like merging(squash) multiple commits into one or editing (edit) the commit messages of previous commits.

So much for the explanation, lets get into the actual commands…

Lets start with rebasing

git rebase -i HEAD~n

Here put n as the number of commits you want to go back to, look at the screenshot for the example, the “-i” flag is for interactive, this will become clearer as we progress


Ignore the text after the command, this comes after the next step


Here you’ll see the list of commits

 e #edit
 p #pick
 s #squish

These are the options you can apply on each commit

edit – to edit the commit message

pick – this commit is used

squish – this is used to merge useless commits into the previous commit (really useful to cleanup the commit history)


You might face some merge conflicts, fix them and proceed

Check this blog post on how to resolve merge conflicts: Working with github and git


After this, you will see screens to select the commit messages for the squishes and edits

Delete the text you don’t want, or simply comment it out and write a new commit message as needed

new commit message

Now for the final step Forced Push

This is used to rewrite the commit history on the actual git repo on whatever online git management site you use.

git push -f origin branch

here branch is the branch name on which you want to make the forced push

the “-f” flag is for … you guessed it force

forced push


—force-with-lease :


is a safer alternative to –force, as it does not allow the force push if someone else made a commit which was not taken care of in rebase. Using –force would have deleted that commit.


Rebasing and forced push will help clean up your mess, to help maintain a neat and tidy repo.

There are also other uses of rebasing which will be covered in a future blog.

A word of caution : Always use forced push with caution, as you might end up messing up the main repo.

May the -f  be with you

Leave a Reply

Your email address will not be published. Required fields are marked *