Sentry Answers>Git>

Revert a Git repository to a previous commit

Revert a Git repository to a previous commit

David Y.

The Problem

How do I revert a Git repository to a previous commit?

The Solution

In Git, the word “revert” has a special meaning. You can use the git revert command to return your repository’s files to a previous state without rewriting the commit history. This is done by creating new commits that do the opposite of existing commits, i.e. removing lines and files that were added and adding lines and files that were removed.

To revert the most recently created commit, you can specify its hash or use HEAD:

Click to Copy
git add . git commit -m "This commit is a mistake" git revert HEAD # will create a new commit doing the opposite of the one above

To revert multiple recent commits, you can specify a range, from oldest to newest. One new commit will be created for each reverted commit.

Click to Copy
git revert HEAD~3...HEAD # revert the last three commits

git revert is a good way to restore a previous state while retaining the repository’s edit history. However, in some cases, you may prefer to delete previous commits rather than reverse them. To do this, you can use git reset --hard, specifying the commit to return to:

Click to Copy
git reset --hard HEAD~

This will return the repository’s files to their previous state and remove the most recent commit from the current branch’s history. For more on git reset, take a look at our answer for undoing Git commits.

Further Reading

If you’re looking to get a deeper understanding of how application performance monitoring works, take a look at the following articles:

  • Syntax.fmListen to the Syntax Podcast
  • ResourcesWhat is Distributed Tracing
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

© 2024 • Sentry is a registered Trademark of Functional Software, Inc.