“git revert” reverses a commit only in terms of the state of the commits retaining the history of previous commits. It adds an extra commit that is the reverse of the reverted commit. In essence, we are in a state where the reverted commit is not present functionality-wise. However, history still shows it. Unlike “git reset” (hard and soft), you do not lose the commit in this case. Let us see with a hands-on example.
Consider this initial arrangement of a repository with the name repoone. It has four commits, as shown. There are a total of six files and one directory, as shown.
~/repoone$ git log --oneline 908d6ac (HEAD -> main, origin/main, origin/HEAD) Third commit in main 42296d0 Second commit in main 453424e This is first commit 2673111 Initial commit ~/repoone$ ls dirone filefive filefour filesix filethree filetwo README.md
Use “git show” on the latest commit. You would see that it has added two files filefive and filesix.
~/repoone$ git show 908d6ac commit 908d6ac779f38123751ddd70d6107bb43cc832a1 (HEAD -> main, origin/main, origin/HEAD) Author: paperspace <Code Version Master> Date: Sat Sep 10 05:15:28 2022 +0000 Third commit in main diff --git a/filefive b/filefive new file mode 100644 index 0000000..e69de29 diff --git a/filesix b/filesix new file mode 100644 index 0000000..e69de29
Issue “git revert” now, it indeed deletes the files – filefive and filesix and reverts a commit.
~/repoone$ git revert 908d6ac Removing filesix Removing filefive [main 2648ebd] Revert "Third commit in main" 2 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 filefive delete mode 100644 filesix
But in the log of commits, you would see that the fourth commit is not gone. It is still in history, and a new fifth commit is present now. It is a commit that reverses the fourth commit action.
~/repoone$ git log --oneline 2648ebd (HEAD -> main) Revert "Third commit in main" 908d6ac (origin/main, origin/HEAD) Third commit in main 42296d0 Second commit in main 453424e This is first commit 2673111 Initial commit ~/repoone$ ls dirone filefour filethree filetwo README.md
What is the use of git revert?
- You can test the software without a specific commit while still having it in history. You can revert anytime you need.
- You can create a duplicate of the branch after the revert operation. You can revert to the original state because the history is present.
- Unlike resetting hard or soft, you did not lose the commit.