Git : how to move back in your commits

Now that we know how to commit and push our changes, lets into few scenarios when things get wrong and you want to revert back.

– I messed up your working file but didnt staged it yet – So you were working on your code for some time, tested it locally which didnt worked, and worse you closed the file so you cant do ctrl+z, so how to go back

$git checkout <path/to/file>


If you want to revert all your untracked files you can use
$ git clean -df //This will remove all untracked files

– I messed up my working file and have staged it.


Here you can first do a git reset HEAD and the checkout that file like following


I messed up my working file and have commited it


You can use

$git checkout HEAD^ <path/to/file>


HEAD^ represents the prior commit.

$git checkout <sha-of-commit> <path/to/file>  //Revert to version of file from specific commit

Please note that the above 2 commands only moves your HEAD to a previous version. Your commit (wrong ones) are still there. So what if you want to get rid of those commits. For that you can use git RESET command

I messed up my file, commited it , now I want it back in my staging env.


For getting file back in my staging env we can use git reset –soft


Now you can choose to go back to unstaged version or anything you want.

I messed up my working file, commited it and want to remove that commit and rever my file back t previous version


We can use git reset –hard


Also FYI

$git reset –hard HEAD^ //Delete last commit. Changes files to state of previous commit.

$git reset –hard HEAD^^^ //Delete last three commits. Changes files to state prior to last third commit.

$git reset –hard <sha-of-commit> //Returns files to state they were in after specificed commit

Now , suppose you did some wrong commits and the pushed it to your remote branch. How to remove those commits from there, well for most of the time, you will be correcting those files and pushing it again, which is correct. If for some reason you want to remove the commits from remote too, you can ‘git reset’ your local branch, and you git push –force your revised local branch to the remote, like follwing:

$ git reset HEAD^ –hard
$ git push origin -f

Also you can play with sha-ids instead of HEAD. git interprets x^ as the parent of x.

There are other ways to achieve this like revert, rebase etc. We will look into these later posts.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: