How to recover `.git/index` locally? How to recover `.git/index` locally? git git

How to recover `.git/index` locally?


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

git reset         # re-scan the working directorygit add -u        # update the index


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.


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).