Git - How to undo the last commit

Git - How to undo the last commit


Removing your latest commit from your local (or remote) Git repository is a common task when you've committed the wrong files and/or code. Here are a few short and sweet examples using Git that show how to undo a commit (without twelve paragraphs of theory explaining it).


Undo last commit from local Git repository


You just executed a git commitYou did not execute a git push command. You want to undo your changes. If these are all true, you likely want to either completely discard your changes and the local commit OR only discard the local commit and keep your changes. This tends to happen when you've spent hours in a rabbit hole or your cat jumped on the keyboard while you had your git prompt open.

Solution 1: Discard everything, nuke the local commit and file changes

Run the git reset --hard command. This will undo all changes to the file system and delete your local commit.

git reset --hard

Solution 2: Discard only the local commit, keep file changes

Run the git reset or git reset --soft command. This will delete your local commit and keep all changes made to the file system.

git reset --soft


Undo last commit from remote Git repository


You just committed your code, ran a git push command, started pouring a fresh cup of coffee and BOOM you just realized there’s a problem with your commit. Now you need to undo the commit and push it to the server quickly. If you are slow, surely one of your coworkers will pull it and publicly shame you.


Execute a git revert command. This will create a new commit that is the exact opposite of the commit that had your erroneous changes.

git revert

At this point you want to push this new commit (which reverts your previous commit) to the git remote. Executing a git commit and git push command will achieve this.

git commit
git push