How to undo the last local commit in Git?

Posted January 8, 2020 2.4k views
Linux BasicsGitLinux Commands

Recently I was making some changes to a local git repository and I committed some changes and files that I should not have committed.

I did not run git push so the changes were only committed to my local Git repository.

So I decided to share how I reverted the last commit here with the community in case someone gets in the same situation.

So rather than wiping out your whole local repo and cloning a fresh copy, you could do the following:

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

1 answer

Of course, as with everything, there are multiple solutions.

But what I would usually do in this case in order to undo my latest commit and then commit my new changes is the following.

  • Let’s say that you made some changes and you committed the changes:
  • git commit -m "Committing the wrong changes"
  • After that if you run git log you will see the history of everything that has been committed to a repository.

  • To undo the last commit, just run the following:

  • git reset --soft HEAD~1

The above command will reset back with 1 point.

Note: the above would undo your commit but it would keep your code changes if you would like to get rid of the changes as well you need to do a hard reset: git reset --hard HEAD~1

  • After that make your new changes

  • Once you are done with the changes run git add to add any of the files that you would like to be included in the next commit:

git add .
  • Then use git commit as normal to commit your new changes:
git commit -m "Your new commit message"
  • After that, you could again check your history by running:
git log

Here’s a screenshot of the process:

Git How to undo latest commit digitalocean

Another approach would be to use git revert COMMIT_ID instead.

Here is a quick video demo on how to do the above:

Hope that this helps!

Submit an Answer