genxgeek
genxgeek

Reputation: 13357

How to recover last commit after git hard reset?

Can I recover the following commit after a hard reset?

Steps:

1) $ (master) // ....made a bunch of changes to files thinking I was working on a branch
2) $ git checkout -b 001-branch  // copy changes to a branch to work with
3) $ (001-branch) // make some more changes to files
4) $ (001-branch) git commit -a -m 'added and changed stuff'
// at this point I was just going to pull force master to latest then rebase my 001-branch off of original master (not the stuff I had modified)
5) $ (001-branch) git checkout master
6) $ (master) git reset --hard HEAD
7) $ (master) git pull
8) $ (master) git checkout 001-branch // go back to my branch and rebase my changes
9) $ (001-branch) // oops...my changes were all kiboshed and I don't see the commit I did per git lg

Any way out of this mess to recover my changes?

Upvotes: 24

Views: 13746

Answers (4)

FelipeC
FelipeC

Reputation: 9488

To see all the changes made to your 001-branch, you can do git reflog 001-branch, however, chances are what you think you did in 001-branch maybe you did another branch, so you probably need to look into all the changes with git reflog.

Upvotes: 27

Jokester
Jokester

Reputation: 5617

Honestly I don't get what happened.

git reflog prints what commits a branch was pointing at. You can use it to find the SHA1 sum of recent local commits.

Upvotes: 4

mvp
mvp

Reputation: 116177

Every time git does something drastic like changing or rewinding branches, it records that in reflog. In other words, carefully inspect output of git reflog, it will tell you all transitions you branch ever had. You can then use git show commit_id to inspect and git checkout commit_id to get back.

Upvotes: 7

chwarr
chwarr

Reputation: 7202

Does git reflog show print the hash of the missing commit? If yes, then git checkout -b recovery-branch commitId will create a new branch pointing to the missing commit. You can then merge as needed.

Upvotes: 23

Related Questions