Lan Lan - 1 year ago 96
Git Question

restore - git reset --hard HEAD^

Unfortunately I did several times

git reset --hard HEAD^
losing a quite big chunk of code in several files. Is there a way to restore those commits or in this case to forward where the HEAD was before, so I can bring up those lines that I lost?

Answer Source

Use the reflog to recover the sha1 of the previous HEAD, e.g.

$ git reflog HEAD -n3
c4090e41 (HEAD -> master) [email protected]{0}: rebase -i (finish): returning to refs/heads/master
c4090e41 (HEAD -> master) [email protected]{1}: rebase -i (start): checkout HEAD~2
b0378a5c [email protected]{2}: commit: Generalise

The article "reflog, your safety net" will be particularly relevant to you. From that article:

The most common usage of this command is that you’ve just done a git reset and moved your HEAD back a few commits. But oops, you need that bit of code you left in the second commit. Crap. Now what?

$ git reflog

You can also use the --all option to get more detailed information about different branches and even the stash

$ git reflog --all

Once you have found the sha1 of the commit you want to go back to, use something like:

git reset --hard 0a1b2c

An example of using this command to quickly pack up your repository used to be found on John Wiegley’s blog, where he compressed his repository with the following commands:

$ git reflog expire --expire=1.minute refs/heads/master
$ git fsck --unreachable      
$ git prune                   
$ git gc                      
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download