How to undo last commit/push to git repository

Was faced with an issue recently where I ‘accidentally’ pushed a ‘bad’ commit to github. Luckily with git its easy to undo such mistakes.

In your working directory type

git push -f origin HEAD^:master

And voilia, your last push was removed.

Note. To sync local changes to match the previous head we can use

git reset HEAD~

Now, lets say you pushed a truckload of crappy commits to the repository. Well, thats not gonna be an issue either, just add more carets for each push you wish to remove.

eg. to remove the last 3 commits

git push -f origin HEAD^^^:master

Did it work for you? share your experience in the comments below.