42

I accidentally deleted .git/index, is there a way to recover it? It's permanently deleted. I haven't committed anything yet.

kenorb
  • 155,785
  • 88
  • 678
  • 743
dyarbrough
  • 771
  • 2
  • 8
  • 14

3 Answers3

62

To rebuild the index file, you can try these two commands:

git reset         # re-scan the working directory
git add -u        # update the index
kenorb
  • 155,785
  • 88
  • 678
  • 743
6

You can recover the index as of the last checkout with git reset. Any content you had added since then is still added, it's in the repository, but the index was the only place that recorded the association of path and content. You can have git fsck drop unreachable objects into a lost'n'found directory, see its docs, then the quickest route over familiar territory is to just drop the content back in the worktree and add it again, git won't duplicate contents but it will recover the index entry.

jthill
  • 55,082
  • 5
  • 77
  • 137
5

I don't think that's possible, not via git anyway (you can try looking inside your Trash directory or whatever means of recovery your filesystem offers). You'll get a new index, though, as soon as you git add something or do something else that requires the index.

If you've lost any of the files that you've git added, you can go through ./git/objects (find .git/objects/ -type f |sed 's:\.git/objects/::; s:/::' ) , inspect the contents of each with git cat-file -p $the_hash, and once you've found the lost one, redirect the output to a file.

(When you git add, a filename entry goes to .git/index and the file contents get stored in .git/objects/. Git index is made of the file name entries of a would-be tree object that gets created when you commit. You can view a human-readable representation of the index with git ls-files --stage).

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
  • 2
    The index has a bit more stuff in it, but yes, it's basically a cache of name-and-hash-es. For some completeness, it's worth mentioning that the index has four possible "slots" per name: slots 1-3 are used only during a conflicted merge, and slot zero is where the normal, next-commit-to-make entry goes. – torek Jul 09 '16 at 00:12
  • 2
    This saved me quite a bit of time. I'd staged some files and realized the repo was in the middle of a cherry-pick, doing a `git cherry-pick --abort` wiped out the index! I used your `find | sed` command to restore the index. Thanks! – legends2k Dec 23 '21 at 06:12