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 <me@me.com>
Date: Thu Nov 4 18:59:41 2010 -0400
blah blah blah...
commit 25eee4caef46ae64aa08e8ab3f988bc917ee1ce4
Author: Me <me@me.com>
Date: Thu Nov 4 05:13:39 2010 -0400
more blah blah blah...
commit 0766c053c0ea2035e90f504928f8df3c9363b8bd
Author: Me <me@me.com>
Date: Thu Nov 4 00:55:06 2010 -0400
And yet more blah blah...
commit 0d1d7fc32e5a947fbd92ee598033d85bfc445a50
Author: Me <me@me.com>
Date: Wed Nov 3 23:56:08 2010 -0400
Yep, more blah blah.
How do revert to the commit from November 3, i.e. commit 0d1d7fc
?
If you want to "uncommit", erase the last commit message, and put the modified files back in staging, you would use the command:
--soft
indicates that the uncommitted files should be retained as working files opposed to--hard
which would discard them.HEAD~1
is the last commit. If you want to rollback 3 commits you could useHEAD~3
. If you want to rollback to a specific revision number, you could also do that using its SHA hash.This is an extremely useful command in situations where you committed the wrong thing and you want to undo that last commit.
Source: http://nakkaya.com/2009/09/24/git-delete-last-commit/
Reverting Working Copy to Most Recent Commit
To revert to a previous commit, ignoring any changes:
where HEAD is the last commit in your current branch
Reverting The Working Copy to an Older Commit
To revert to a commit that's older than the most recent commit:
Credits go to a similar Stack Overflow question, Revert to a commit by a SHA hash in Git?.
I have tried a lot of ways to revert local changes in Git, and it seems that this works the best if you just want to revert to the latest commit state.
Short description:
git revert
does.git checkout <commithashcode>
does.I found a much more convenient and simple way to achieve the results above:
where HEAD points to the latest commit at you current branch.
It is the same code code as boulder_ruby suggested, but I have added
git add .
beforegit reset --hard HEAD
to erase all new files created since the last commit since this is what most people expect I believe when reverting to the latest commit.Say you have the following commits in a text file named
~/commits-to-revert.txt
(I usedgit log --pretty=oneline
to get them)Create a Bash shell script to revert each of them:
This reverts everything back to the previous state, including file and directory creations, and deletions, commit it to your branch and you retain the history, but you have it reverted back to the same file structure. Why Git doesn't have a
git revert --to <hash>
is beyond me.There is a command (not a part of core Git, but it is in the git-extras package) specifically for reverting and staging old commits:
Per the man page, it can also be used as such:
Revert to most recent commit and ignoring all local changes: