Reputation: 29
My git branch was probably in a bad state (incomplete rebase perhaps) and I did not know. I made few changes and then wanted to commit but git complained that that you are in a cherry-picked state, so it can't commit. I googled and found out that if I do a reset --hard
to a remote branch, it would take me out of the bad git state. Before doing that, I had added my changes in the staging area (using git add). But when I did git reset --hard
, my staging area is gone. I cannot find my index files and changes. Is there a way to resurrect the index?
Upvotes: 2
Views: 204
Reputation: 78653
When you git add
a file, it will add that file to the object database and place the object information in the staging area. If you are to subsequently remove that file from the staging area, it is removed only from the index. The file will remain in the object database until it is garbage collected. You can find these "dangling" files using git fsck
.
For example:
If I create a new file and git add
it to my staging area:
% echo "new file" > newfile.txt
% git add newfile.txt
% git ls-files --stage
100644 40ee2647744341be918c15f1d0c5e85de4ddc5ed 0 file.txt
100644 3748764a2c3a132adff709b1a6cd75499c11b966 0 newfile.txt
And then reset to HEAD
, notice that newfile.txt
disappears:
% git reset --hard HEAD
% git ls-files --stage
100644 40ee2647744341be918c15f1d0c5e85de4ddc5ed 0 file.txt
However, running git fsck
will show me objects that are not rooted in my graph, that are "dangling" either because there are commits that are not part of a branch (perhaps I rewrote them) and the objects they reference, or because I git add
ed a file and did not commit it. My newfile.txt
will be among those:
% git fsck
Checking object directories: 100% (256/256), done.
dangling blob 3748764a2c3a132adff709b1a6cd75499c11b966
Unfortunately, its filename is not stored in the object database (since identical contents would have the same object regardless of name), so if you have many dangling blobs, you will have to examine each one:
% git show 3748764
new file
Once I determine which dangling blob it is that I want to recover, I can put it back on the filesystem by redirecting git show
:
% git show 3748764 > newfile.txt
And the file is recovered!
Upvotes: 3