DevPal   Online developer tools

How to undo the most recent Git commit?



As developers, we are often in rush to commit new code changes. That might trick us to create a git commit with unwanted or unacceptable changes. Luckily, Git offers a solution out of the box. The thing is that the command names are not that straightforward as they could be.

In this post we will explain how to undo your last git commit, whether you already pushed it to the remote or not.


How to undo Git commit?

There are a few different solutions how to fix this, but choosing the best one depends on your use case:


Undo Git commit on local or personal branch

When to apply:

  1. If you created a git commit only locally, you haven't pushed it to remote, and you want to undo it.
  2. If you created a git commit, and you pushed it to the remote branch that only you and nobody else uses. And now you want to undo it.

How to undo commit:

git reset <last good COMMIT_SHA>
or
git reset --hard <last good COMMIT_SHA>

Explanation:

This command will move the pointer of your branch to the previous, a good commit. If you pass --hard argument, it will not preserve any changes you made in the mistaken commit, otherwise, it will preserve them as not marked for commit.

In case you are undoing the last commit from remote, personal branch, make sure you are allowed to do git push --force on that repo branch.


Undo Git commit on remote, shared branch

When to apply:

  1. If you created a git commit on a shared branch and you pushed it to remote. And now you want to undo the last commit from it.

How to undo commit:

git revert <COMMIT_SHA>

Explanation:

This git revert command will create an additional commit that contains completely opposite changes from the last commit. That way it will "cancel" the changes from your mistaken commit and will not change the history of the shared remote branch. It will leave the mistaken commit in the git history, but it will not create problems among team members that use that same branch.
Changing the history of shared branches (branches that are used by more than one team member) is highly not recommended, because it can ruin the work other team members started doing and put them in unwanted merge conflicts. And this command avoids that.


Conclusion

Here we showed how to undo git commit, either with git reset or git revert commands. Git showed us that it is a pretty reliable tool that tolerates our small mistakes while using it.