Git Revert & Reset

Git Revert & Reset

Git provides multiple mechanisms for undoing or altering past commits. Two such commands are git revert and git reset.

1. Git Revert: Undo

The git revert command creates a new commit that undoes the changes made in a previous commit. This is a safe way to undo changes, as it does not alter the existing commit history.

Here's a simple example of how to use git revert:

  1. Consider the following Git log:
$ git log --oneline
4f0f15f (HEAD -> master) Third commit
1620b2e Second commit
a4b7f3c First commit
  1. If you want to undo the changes made in the latest commit (the "Third commit" in this case), you would use the git revert command with the commit hash:
$ git revert 4f0f15f
  1. This will open a text editor prompting you for a commit message for this new commit that undoes the previous commit. Once you save and close the editor, Git creates a new commit that undoes the changes of the specified commit. If you look at the Git log again, you'll see a new commit has been added:
$ git log --oneline
8d9a2e6 (HEAD -> master) Revert "Third commit"
4f0f15f Third commit
1620b2e Second commit
a4b7f3c First commit

2. Git Reset: Remove Commit History

Just like nothing has happened! ;)

The git reset command, on the other hand, does alter/remove the commit history. It moves the HEAD pointer back to a previous commit, essentially "forgetting" any commits that may have occurred after the specified commit. Depending on the options used, it can also alter the staging area or the working directory.

Here's a simple example of how to use git reset:

  1. Consider the same Git log as before:
$ git log --oneline
4f0f15f (HEAD -> master) Third commit
1620b2e Second commit
a4b7f3c First commit
  1. If you want to "forget" the latest commit (the "Third commit" in this case), you would use the git reset command with the commit hash:
$ git reset --hard 1620b2e

The --hard option tells Git to not only move the HEAD pointer, but also to update the staging area and the working directory to match the specified commit.

  1. Now, if you look at the Git log again, you'll see the "Third commit" is gone:
$ git log --oneline
1620b2e (HEAD -> master) Second commit
a4b7f3c First commit

Please be cautious when using git reset --hard, as it permanently discards commits and any uncommitted changes in the staging area and working directory.

In a nutshell, git revert is a safe method that undoes the effect of a previous commit by adding a new commit, whereas git reset alters the commit history by moving the HEAD pointer to a specific commit, discarding all commits that occurred after.

ย