Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
in DevOps and Agile by (29.3k points)
edited by

How do I revert from my current state to a snapshot made on a certain commit?

If I do git log, then I get the following output:

$ git log

commit a867b4af366350be2e7c21b8de9cc6504678a61b`

Author: Me <[email protected]>

Date:   Thu Nov 4 18:59:41 2010 -0400

blah blah blah...

commit 25eee4caef46ae64aa08e8ab3f988bc917ee1ce4

Author: Me <[email protected]>

Date:   Thu Nov 4 05:13:39 2010 -0400

more blah blah blah...

commit 0766c053c0ea2035e90f504928f8df3c9363b8bd

Author: Me <[email protected]>

Date:   Thu Nov 4 00:55:06 2010 -0400

And yet more blah blah...

commit 0d1d7fc32e5a947fbd92ee598033d85bfc445a50

Author: Me <[email protected]>

Date:   Wed Nov 3 23:56:08 2010 -0400

Yep, more blah blah.

How do you revert to the commit from November 3, i.e. commit 0d1d7fc?

1 Answer

+2 votes
by (50.2k points)

If you need to switch temporarily to a committed branch

$git checkout <commit-id>

commit id will be available in

$git log

and it should be the id of the commit that you need to revert.If you need to make commits, go ahead and make a new branch 

$ git checkout -b <old-state> <commit-id> (ie ;- $git checkout -b master <commit-id>).

To go back, you just checkout the branch that you were on again. (If you've made changes, when switching branches, you'll have to deal with them as appropriate. You could reset to throw them away, you could commit them to a branch there if you want a branch there.)


If you need to reset all mess that you have created during revert use $git reset --hard <commit-id>. Do only if you have committed the work that you need further. Also, you can stash, pop if there is a work to save

This saves the modification, then re-applies that patch after resetting. If you already published the commits then you need to undo the published commits with new commits.

Undoing published commits can be done by using revert command.

$git revert <commit-id>

you can give the reverted commits by giving ranges.

$git revert HEAD~2...HEAD.

Reverting a merge commit

$git revert -m 1 <merge_commit>

 You can get your index and work tree into the desired state, without changing HEAD

$git checkout 0d1d7fc32 .(commit-id)

then finally commit using $git commit, thus, you can undo published commits.

Browse Categories