1

I have tried to commit my source to github, below is what I have done:

  1. git add .
  2. git reset --hard

In the first step I add the file that will be commited. But after that I don't want to commit it, and search the way to backout the file added. So I tried to use "git reset --hard".

And the result is all my data has been removed. Is there anyway to undo 2nd step and recover my data?

EmBeCoRau
  • 327
  • 1
  • 4
  • 14

1 Answers1

3

I have a solution, if you haven't run git gc!

When you run git add . it will create new objects for any files with modified content. These will show up in .git/objects/*/*.

Use this find command to find the most recent changes to your .git repo:

find .git -printf "%T@ %Tc %p\n" | grep git/objects/../ | sort -n | tail -100

You will see an output like this, which is each "blob" that has been added to the git "database" sorted in date order:

1555137117.9174205020 Sat 13 Apr 2019 02:31:57 AM EDT .git/objects/27/0e06d22c74316a523a3d5faf1e525730f30063
1555137119.0064516220 Sat 13 Apr 2019 02:31:59 AM EDT .git/objects/d8/dee4a715c2064caee8662dd8ccf5dc612cb90c
1555137120.8755050290 Sat 13 Apr 2019 02:32:00 AM EDT .git/objects/00/02959bbbcd5a170ab04a32093ba8c5abca1089
1555137310.5479249430 Sat 13 Apr 2019 02:35:10 AM EDT .git/objects/c3/a6bbbb091403d18550cc729a98e90a643bfa66

Now, all that is left is to extract the content of the objects one at a time until you find what you are after:

Take the .git/objects/c3/a6bbbb091403d18550cc729a98e90a643bfa66 and extract the object ID from it by combining the c3 with the a6bbb.... Pass this to git cat-file

git cat-file -p c3a6bbbb091403d18550cc729a98e90a643bfa66

And alas, the content of the file at the point you ran git add . will be dumped out to your terminal! (use bash redirection > to write that to a file)

gahooa
  • 131,293
  • 12
  • 98
  • 101
  • This should probably be posted as an answer to the nominated duplicate instead. (Though the accepted answer is vaguely similar.) – tripleee Apr 13 '19 at 06:55
  • Hi sir, I'm trying to use `git cat-file`, and I can see the content of the file in terminal, but I can not write it to file using `>`. Beside that, in the source I have about 7000 file, so I have to write each file in there by hand ? – EmBeCoRau Apr 13 '19 at 06:56