Sometimes you may need to undo git commit, or revert last made changes in your git repository. There are many different ways to undo git commit. In this article, we will look at the different ways to revert git commit, along with what they mean.
How to Undo Git Commit
We will look at different use cases to undo git commit.
Git Soft Reset
If you need to undo last commit but preserve all changes made for that commit, run the following git reset command with –soft option. You need to also specify which commit (e.g. HEAD) to undo and also by how many commits (e.g. 1)
$ git reset --soft HEAD~1
Now when you run git status command, you will see all changes of your last commit, listed as uncommitted changes. That is, the changes you made in your last commit will be still present in your index but not committed.
Undo Multiple commits
You can use git reset to undo any number of last commits. For example, if you need to undo last 5 commits, replace 1 with 5 above.
$ git reset --soft HEAD~5
Also read : How to Delete lines in vi editor
Git Hard Reset
If you need to undo last commit as well as remove all its changes, then use the option –hard along with git reset command.
$ git reset --hard HEAD~1
Be very careful when you use this command, you will lose all changes you made in your last commit, and will not be able to recover them.
Also read : How to Install NGINX with GeoIP module
Git mixed reset
If you need to undo last commit but keep changes in working directory and not in your index then use –mixed option with git reset
$ git reset --mixed HEAD~1
Git Revert
Git Revert is another command to revert last commit. Unlike git reset it reverts your last commit and saves the changes as a new commit in your commit history.
$ git revert HEAD
git revert will undo only 1 commit at a time. If you want to revert multiple commits, you will need to run the git revert command again and again.
Also read : How to run multiple websites on Apache server
Git Reset vs Git Revert
Git reset will undo the last commit and remove its entry from your commit history, whereas git revert will undo the last commit and add them as new commit. It is advisable to use git revert when making changes to public repositories so that everyone knows that a commit was reverted. If you use git reset, it will remove the commit from your history and it will appear as if the commit never happened. Git reset is advisable while using private repositories and branches.
Also read : How to Block IP by Country
In this article, you have learnt the different ways to undo your git commits. You have also learnt which one is to be used under what circumstances. We have also provided the difference between git revert and git reset commands.
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.