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.
$ 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 revert | git reset |
|---|---|
| Adds a new commit that undoes the change | Moves the branch back and removes commits |
| History is kept | History is rewritten |
| Safe for pushed (shared) branches | Only for local commits |
| Can undo any commit in the middle | Mostly for the latest commits |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |