When you worked on a Git repository, sometimes you want to undo your last commit. Fortunately, Git has a special pointer called HEAD which points to the newest commit in the local branch you’re working on.
To undo a commit, you have to point the HEAD to the previous commit ID of the current working branch.
This tutorial will show you the way to undo the last commit in Git.
Undo the Last commit
You can use the following command to undo the changes in Git:
$ git reset <commit-id>
There are some additional arguments that come along with the git reset command:
–soft: Update the HEAD to a given commit while the current working directory and staging index are not changed.
–mixed: Update the HEAD to a given commit and change the staging index to the specified commit while the current working directory is not changed. This option is the default operation when using the git reset command without any argument.
–hard: Update the HEAD and change both of the current working directory and staging index to the specified commit. When using this option, bearing in mind that all the local changes you have not committed will be lost.
To avoid losing the changes you made on the current working directory and staging index when undoing the last commit, let’s run the following command:
$ git reset --soft HEAD~1
HEAD~1 means one commit before HEAD (the previous commit of the latest commit).
Before undoing the latest commit:
After undoing the latest commit using the –soft option:
If you don’t want to keep the changes you made on the current working directory and local files that haven’t been committed, run the git reset command with the –hard option:
$ git reset --hard HEAD~1
You’ve gone through the detail of using the git reset command to undo the last commit in Git. It’s really a powerful command when working with Git.
If you have any questions, please leave your comment in the below section.
System Engineer with 6 years of experience in software development, specializes in Embedded Linux, C/C++, Python, Go, and Shell Scripts. He has a solid background in Computer Networking, OpenStack, Kubernetes, Docker/Container, CI/CD, and Google Cloud as well. Now, he is Head of GDG Cloud Hanoi – a non-profit community of cloud developers who meet/share ideas on everything Google Cloud Platform related.