Reputation: 423
I was working with git bash, rebasing and stashing my changes when suddenly my PC crashed. After the restart, the disk was repairing, but when it loaded the repository no longer worked, git commands returned:
fatal: not a git repository (or any of the parent directories): .git
All the files that I have not committed are now blank, the changes are gone. HEAD files and stash are also corrupted. I am in a panic mode.
What can I do in this situation to recover lost files and restore the repository to the previous state?
Upvotes: 0
Views: 356
Reputation: 487725
First things first: Make a full copy of the repository in case attempts to fix it break it further.
What makes Git say fatal: not a git repository (or any of the parent directories): .git
?
There could be multiple causes for the problem, and it's possible that a simple fix doesn't work. However, in my experience, the most common cause for this problem has a fix that is nearly trivial: the .git/HEAD
file is missing or invalid. You can simply create one. If you remember which branch you were on, use that name, otherwise use the main (master
or main
) branch name:
$ echo "ref: refs/heads/main" > .git/HEAD
If this is not sufficient, the other things that Git requires in the .git
directory are an objects/
subdirectory and a refs/
subdirectory. Unfortunately, if these are damaged to the point that they don't exist, there's never a simple repair.
If this does get Git to believe that the directory is a Git repository, it's a good idea to run git fsck
afterwards. This may report "dangling" items, which are actually rather normal; if it reports "broken" items or "bad" items, something is actually wrong. Still, you can at least get whatever you can get, from the damaged repository.
In general, the best way to deal with a wrecked Git repository is to make another clone, but of course if you have not been committing, and duplicating those commits elsewhere (e.g., via git push
or regular backups), you might lose a lot this way.
Upvotes: 1