Recovering added/staged file after doing git reset --hard HEAD^?

Viewed 61961

I added a new file F1 and made changes to another file F2 but then did a git reset --hard HEAD^ and I have lost all the changes to the files.

Is there some way, I can get them back?

I did look at a related question here: How can I undo git reset --hard HEAD~1? but, that question assumes that the one has done a Git commit.

5 Answers

You can (with some work) recover state of file at the last "git add <file>". You can use

$ git fsck --cache --no-reflogs --lost-found --dangling HEAD

and then examine files in '.git/lost-found/other' directory.

Please read git fsck manpage.

Actually, if you've added the object to the index (by using git add), there is a blob created for that state of the object - but there is no tree (and thus, commit) object that is referring to it. This is how one gets a 'dangling' loose object file, and if you run git fsck it will show you the unreferenced blob (git gc will delete these types of objects if it is run).

Because of this, you can use the reflog, if you have it enabled, to try and restore the index state for your file F1 that has been added. If you haven't added F2 at all, then as Greg said, git doesn't know anything about it and you're out of luck there.

Related