Undo and revert pushed Git commits

If you need to undo a git push, you only have two options: revert the pushed commit or reset it.

The option you choose to undo a pushed commit depends on the following three factors:

  • How much control you have over the remote repository.
  • Whether or not others have fetched or pulled the pushed commit to undo.
  • Whether or not you want to permanently delete the pushed Git commit.

Choosing the wrong option to undo a git push can have serious ramifications upon code shared throughout the team.

How to undo a git push

To undo a pushed Git commit, either of the following two options are valid, although they each come with their own benefits and drawbacks:

  1. Undo the git push with a local git revert command and push back normally.
  2. Undo the pushed Git commit with a reset and push back with force.

How to revert a pushed commit

If you have pushed a bad commit to GitHub or GitLab, the easiest thing to do is simply issue Git's revert command and push back to the server.

git revert
git push origin

When the git revert command is issued without any other parameters, it undoes the changes that were part of the previous commit and creates a new commit to denote the change.

When you push back to the server, anyone who looks at your latest commit will not see the code that was part of the prior git push.

However, the old commit remains on the server. Anyone can still see the pushed commit you're trying to undo.

Forcefully undo a git push with reset

If you want to permanently delete a pushed Git commit from the server, you must perform a hard reset and then push back to the server with force.

git reset --hard
git push --force origin

However, pushing back to the server with force is a destructive move, as it rewrites history to permanently delete the pushed commit.

Chart showing a git reset
A hard git reset along with a forced push is one way to undo a pushed Git commit.

If others have pulled from the shared repository and have a copy of the pushed commit you want to undo, they will have problems then next time they pull or fetch. Team members might need to perform a new git clone to fix a corrupt Git commit history caused by a forced push.

Unfortunately, if the goal is to completely delete the pushed commit, a reset and push with force is the only option.

But to be safe, the best way to undo a git push is with git revert. Your fellow developers will appreciate it.

Cameron McKenzie has been a Java EE software engineer for 20 years. His current specialties include Agile development, DevOps and container-based technologies such as Docker, Swarm and Kubernetes.

View All Videos