views:

2562

answers:

3

This is probably the simplest newbie question.

I have a project in which I've run git init. After several commits, I do a git status which tells me everything is up to date and there are no local changes.

Next, I make several consecutive changes and realize I want to throw everything away and get back to my original state. Will this command do it for me ?

git reset --hard HEAD
+12  A: 

If you want to revert changes made to your working copy, do this:

git checkout .

If you want to revert changes made to the index (i.e., that you have added), do this:

git reset

If you want to revert a change that you have committed, do this:

git revert ...
1800 INFORMATION
Awesome. #1 is what I want.
Jacques René Mesrine
Short and clear:)
Ikaso
+1  A: 

Look into git-reflog. It will list all the states it remembers (default is 30 days), and you can simply checkout the one you want. For example:


bash-3.2$ git init > /dev/null
bash-3.2$ touch a
bash-3.2$ git add .
bash-3.2$ git commit -m"Add file a" > /dev/null
bash-3.2$ echo 'foo' >> a
bash-3.2$ git commit -a -m"Append foo to a" > /dev/null
bash-3.2$ for i in b c d e; do echo $i >>a; git commit -a -m"Append $i to a" ;done > /dev/null
bash-3.2$ git reset --hard HEAD^^ > /dev/null
bash-3.2$ cat a
foo
b
c
bash-3.2$ git reflog
145c322 HEAD@{0}: HEAD^^: updating HEAD
ae7c2b3 HEAD@{1}: commit: Append e to a
fdf2c5e HEAD@{2}: commit: Append d to a
145c322 HEAD@{3}: commit: Append c to a
363e22a HEAD@{4}: commit: Append b to a
fa26c43 HEAD@{5}: commit: Append foo to a
0a392a5 HEAD@{6}: commit (initial): Add file a
bash-3.2$ git reset --hard HEAD@{2}
HEAD is now at fdf2c5e Append d to a
bash-3.2$ cat a
foo
b
c
d
William Pursell
Very useful. Thanks.
Jacques René Mesrine
+2  A: 

Note: You may also want to run

git -f clean

as

git reset --hard

will not remove untracked files, where as git-clean will remove any files from the tracked root directory that are not under git tracking. WARNING - BE CAREFUL WITH THIS! It is helpful to run a dry-run with git-clean first, to see what it will delete.

This is also especially useful when you get the error message

~"performing this command will cause an un-tracked file to be overwritten"

Which can occur when doing several things, one being updating a working copy when you and your friend have both added a new file of the same name, but he's committed it into source control first, and you don't care about deleting your untracked copy.

In this situation, doing a dry run will also help show you a list of files that would be overwritten.

Antony Stubbs