Git Revert

The git revert command undoes the changes of an old commit by creating a new commit that does the opposite. The old commit stays in the history. This is why revert is the safe way to undo something which is already pushed and shared with other people.

Syntax

git revert <commit>
git revert HEAD
git revert HEAD~2
git revert --no-edit <commit>
git revert -m 1 <merge-commit>

Revert a commit

We have three commits. The middle one, “Add debug file”, was a mistake. We can undo only that commit, and keep the commits before and after it.

Terminal output

$ git log –oneline
07bd72c (HEAD -> main) Add search page
f5d75e9 Add debug file
9434c7a Add login page
$ git revert HEAD~1 –no-edit
[main 33ce8da] Revert "Add debug file"
Date: Sat Jan 10 11:38:00 2026 +0000
1 file changed, 1 deletion(-)
delete mode 100644 debug.txt
$ git log –oneline
33ce8da (HEAD -> main) Revert "Add debug file"
07bd72c Add search page
f5d75e9 Add debug file
9434c7a Add login page
$ ls
login.txt
search.txt

The file debug.txt is gone, but the history still shows both the bad commit and the new revert commit. The other files are not touched.

Revert the last commit

git revert HEAD

Revert more than one commit

git revert HEAD~3..HEAD
git revert --no-commit HEAD~3..HEAD

The option --no-commit (or -n) applies the changes but does not make the commits, so you can join all the reverts in one commit.

Revert a merge commit

A merge commit has two parents, so Git does not know which side to keep. You must tell it with -m. Usually -m 1 keeps the main branch side.

git revert -m 1 <merge-commit-hash>

When there is a conflict

If the later commits changed the same lines, Git stops and shows a conflict. Solve it like a normal merge conflict, then run git revert --continue. To cancel, use git revert --abort.

git revert vs git reset

git revertgit reset
Adds a new commit that undoes the changeMoves the branch back and removes commits
History is keptHistory is rewritten
Safe for pushed (shared) branchesOnly for local commits
Can undo any commit in the middleMostly for the latest commits
Note: If you made a bad commit and already pushed it, use revert. If you did not push it yet, git reset gives a cleaner history. Next: Git Branch.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.