The Problem
How can you revert a Git repository to a previous commit?
The Solution
In Git, “revert” has a distinct meaning. The git revert
command allows you to return your repository’s files to a previous state without altering the commit history. This is achieved by creating new commits that undo the changes of previous commits, effectively removing lines and files that were added and adding lines and files that were removed.
To revert the most recent commit, you can use its hash or the HEAD
reference:
git add .
git commit -m "This commit is a mistake"
git revert HEAD
This command creates a new commit that undoes the changes of the most recent commit.
To revert multiple recent commits, you can specify a range, from the oldest to the newest. This will create one new commit for each reverted commit:
git revert HEAD~3...HEAD
The git revert
command is useful for restoring a previous state while keeping the repository’s edit history intact. However, there are situations where you might want to completely remove previous commits instead of reversing them. For this, you can use the git reset --hard
command, specifying the commit to return to:
git reset --hard HEAD~
This command reverts the repository’s files to their state at the specified commit and removes the subsequent commit from the current branch’s history. For more information on git reset
, refer to our guide on undoing Git commits.