Last updated on October 6th, 2020
Image Credits: Altassian Tutorial.
If you are a web developer or a software engineer, it is very likely that you are pushing a lot of commits to your Git repository every day. Sometimes you committed some files that should not be pushed to your Git repository or you may want to perform additional changes before issuing the commit. Here is how you can revert a commit to GIT.
How to Access the Last Commit
To get the hash of the specific commit you can run
git log
You can simplify the output by running
git log --online
To test a specific commit (e.g.: <before last commit hash>
), that you think has the last working version, you can type the following:
git checkout <commit hash>
How to Revert or Undo the Last Commit
You can undo or revert the last commit by using the commit hash that you get from the git log
command:
git revert <commit hash>
This command will create a new commit with the “Revert” word in the beginning of the message.
You can check the status of your repository after this command
git status
You’ll notice that you have the HEAD detached at the commit you tested before.
To fix this and attach back the HEAD to your working repository, you should check out the branch you are working on:
git checkout <current branch>
Common Options
-e
--edit
With this option, git revert will let you edit the commit message prior to committing the revert. This is the default if you run the command from a terminal.
--no-edit
With this option, git revert will not start the commit message editor.
-n
--no-commit
Passing this option will prevent git revert
from creating a new commit that inverses the target commit. Instead of creating the new commit, this option will add the inverse changes to the Staging Index and Working Directory. These are the other trees Git uses to manage state the state of the repository.
You can read more about the git revert tutorial by Atlassian.