How to Revert a Git Repository to a Previous Commit (Short Answer)


Scenario A: Temporarily Switch to a Different Commit
1
$ git checkout 0d1d7fc32

The above command will:

  • checkout the desired commit
  • detach your HEAD (leave you with no branch checked out)
Scenario B: Hard Delete Unpublished Commits
1
$ git reset --hard 0d1d7fc32

The above command will:

  • destroy any local modifications
  • if you want to keep uncommitted work, use git stash
Scenario C: Undo Published Commits With New Commits
1
$ git revert 0d1d7fc32 25eee4ca

or

1
$ git revert --no-commit 0d1d7fc32..HEAD

or

1
$ git revert -m 1 <merge_commit_sha>

The first command will:

  • create two separate revert commits
  • revert the two commits

The second command will:

  • revert everything from the HEAD back to the commit hash
  • --no-commit flag lets git revert all the commits at once

The third command will:

  • revert a merge commit




Related Posts

What is the Difference Between Git Pull and Git Fetch (Short Answer)

Short answers to the question what is the difference between...

How to Revert a Git Repository to a Previous Commit (Short Answer)

Short answers to the question how to revert a git...

How to Modify Existing Unpushed Commit Messages (Short Answer)

Short answers to the question how to modify existing unpushed...

How to Undo a Git Add Before Commit (Short Answer)

Short answers to the question how to undo a git...

How to Rename a Local Git Branch (Short Answer)

Short answers to the question how to rename a local...

How to Delete a Git Branch Locally and Remotely (Short Answer)

Short answers to the question how to delete a git...