Software Engineering for Self-Directed Learners »

Tools → Git and GitHub →

Reverting a Specific Commit


Git can add a new commit to reverse the changes done in a specific past commit, called reverting a commit.

This lesson covers that part.

When a past commit introduced a bug or an unwanted change, but you do not want to modify that commit — because rewriting history can cause problems if others have already based work on it — you can instead revert that commit.

Reverting creates a new commit that cancels out the changes of the earlier one i.e., Git computes the opposite of the changes introduced by that commit — essentially a reverse diff — and applies it as a new commit on top of the current branch. This way, the problematic changes are reversed while preserving the full history, including the "bad" commit and the "fix".

C3
|
C2
|
C1


[revert C2]

R2This commit is the reverse of C2
|
C3
|
C2
|
C1

HANDS-ON: Revert a commit

0 Preparation: Run the following commands to create a repo with a few commits:

mkdir pioneers
cd pioneers
git init

echo "hacked the matrix" >> neo.txt
git add .
git commit -m "Add Neo"

echo "father of theoretical computing" >> alan-turing.txt
git add .
git commit -m "Add Turing"

echo "created COBOL, compiler pioneer" >> grace-hopper.txt
git add .
git commit -m "Add Hopper"
C3HEADAdd Hopper
|
C2Add Turing
|
C1Add Neo

1 Revert the commit Add Neo.

You can use the git revert <commit> command to revert a commit. In this case, we want to revert the commit that is two commits behind the HEAD.

git revert HEAD~2

What happens next:

  1. Git prepares a new commit which reverses the target commit
  2. Git opens your default text editor containing a proposed commit message. You can edit it, or accept the proposed text.
  3. Once you close the editor, Git will create the new commit.

In the revision graph, right-click on the commit you want to revert, and choose Reverse commit...


A revert can result in a conflict, if the new changes done to reverse the previous commit conflict with the changes done in other more recent commits. Then, you need to resolve the conflict before the revert operation can proceed. Conflict resolution is covered in a later topic.