How to use Git Revert?

The “git revert” is a command used to undo a specific commit. It creates a new commit that inversely applies the changes made by the commit you want to revert. It does not erase the commit from the project’s history but it removes all the changes made by the targeted commit. To run the command you must have an Id number of the commit you want to revert. For e.g. if a commit added a file to the repository then the command will remove that file.

Basic syntax:

git revert <commit-hash>

In the above syntax “commit-hash(or commit ID)” is a 40-character string of hexadecimal characters that uniquely identifies a particular commit you want to revert.

Steps to use the Git Revert command:

step 1: Use the below command to identify the commit you want to revert

git log

Or if you want to revert the most recent commit in the current branch then use HEAD as a reference.

git revert HEAD

step 2: Now perform the revert operation on the identified commit using the below command:

git revert <commit-hash>

Note- Replace with the hash or commit ID of the commit to revert.

A text editor will open to provide a commit message for the new revert commit.

step 3: Save the commit message and close the editor.

step 4: Now push the changes to the remote repository using the below command:

git push origin <branch-name>

Note that “Git revert” is a safe way of undoing the changes without losing the project’s history in place of the “Git reset” command. Let’s understand what’s the difference between “git revert” and “git reset”.

Comparing with Git Reset

Both of the git commands serve different purposes and have distinct effects on the repository. The notable difference between them is when you use “git revert” for a specific commit, only the changes associated with that commit are undone without losing the history. But “git reset” allows you to go back to a specified commit by removing any other commits on its way and rewrites the history. Instead of using “Git Reset”, “Git Revert” is a good option as it helps in tracking the changes or finding bugs by using the history of a project.