How to do rollbacks in GIT (in other words - oops, I shouldn't have done that!)
This is divided into two main sections. How to rollback before the code has been committed, and how to rollback after the code has been committed.
BEFORE you have committed the code
You have already staged a change using “git add”. You don’t want it staged anymore:
git reset
$ git reset HEAD filename.txt
You haven’t staged changes yet, but want to rollback your changes to filename.txt:
git checkout
$ git checkout -- filename.txt
OK, why the two dashes??? Well, if you think about it, the ‘checkout’ command is usually used to switch branches. The two dashes tells it otherwise.
AFTER you have committed the code
You have committed code you shouldn’t have. Oh dear. You have some choices:
git revert
‘git revert’ will create a new commit which undoes a specifc commit that you pass to it. The usual use is to undo the last commit:
$ git revert HEAD
If you need to undo a commit that happened before the last commit you can pass it a caret (Bugs Bunny) or a specific SHA1 of the commit you want to undo:
$ git revert HEAD^
or:
$ git revert 16829a6f
If you rollback to a commit other than the last one, and there are merge conflicts created by undoing the change, you will have to deal with those at the time of your new commit (this revert one).
git commit —amend
‘git commit —amend’ is another command that allows you to change your last commit. For example, if I forgot to stage a file for the last commit and I need to edit the commit message:
$ git commit -m 'initial commit' $ git add filename.txt $ git commit --amend
It will open your default text editor and allow you to edit the comment. The previous commit is overridden by adding my new ‘filename.txt’ and now has my new commit message.
git reset —hard
This will reset the files, and the commits. Pass in the tag, branch, or commit SHA1:
$ git reset --hard (tag/branch/commit id)
Create a new branch and checkout your chosen commit into that
First, rename your master branch:
$ git branch -m mynewbranch
Check out your good commit (the one you want to use):
$ git checkout f1e4ab2b22
Make this commit you just checked out your new master branch:
$ git checkout -b master
That’s it. You still have your ‘mynewbranch’ branch, so if you want to get rid of it now, do this:
$ git branch -D mynewbranch
Note: You will probably need to run:
$ git push -f origin master
to get master to look like it did at the specified commit because of the non-fastforwards.

