Boyan Iliev

How to Undo Your Most Recent Local Commits in Git

Created July 14, 2021

Introduction

Git is probably the most well-known and used version control system. It makes working on a single project with other developers much easier because Git tracks all the changes you make and commit to any of the files.

But what happens when you commit a file by accident and now you want to undo it. well, Luckily for us, there are quite a few options we have.

git reset HEAD~

This command will undo your last commit, and it will also leave your working tree untouched. So the files that you have changed won't be deleted and you can commit them later on.

git reset --hard HEAD~

This command is going to undo your last commit and delete it completely. But don't worry if you deleted a commit by accident and you need it back. You can view a list of your commits with the git reflog command. You should see something like this:

afa655d HEAD@{0}: reset: moving to HEAD~1
e22350b HEAD@{1}: commit: fixed bugs...

In this case e22350b is the deleted commit. So now we can write the following command to restore the file:

git reset --hard e22350b

So git reset --hard HEAD~ may seem scary to use at first, but don't worry, commits usually don't get destroyed in Git for 90 days. So even if you delete one by accident, you can go and get it back.

Conclusion

Git is an amazing version control system and everybody should know how to use it. It is used by so many big companies so it will be a huge bonus. I would recommend you check out this opensource ebook about Git and GitHub:

https://github.com/bobbyiliev/introduction-to-git-and-github-ebook

Here is a video you can watch on How to undo your last commit in Git.

I hope that this post has been of help to you to get comfortable undoing your commits and being more confident using Git.