简体   繁体   中英

Restore deleted directory that was never committed

I accidentally added a local directory to my local Git repo.

git add dirName

It added the twenty or so files in that directory. I did not want them added. They had never been added before, and I did not commit them. Instead, I removed them with:

git rm -rf dirName

This successfully removed them from the repo, but to my dismay that directory also appears to have been deleted from disk. They are not in my recycle bin.

Is there any way to get those files back? I have a backup, of course, but I had made quite a few changes to the files since the last backup.

I don't think the accepted answer is entirely accurate. Indeed git rm removes the files from the index, but they usually remain in Git's object database for a while. Unless you force garbage collection, that is.

Have you tried running git fsck to retrieve some dangling blobs or dangling trees ?

$ git init test
Initialized empty Git repository in D:/DOCUME~1/T012345/LOCALS~1/Temp/test/.git/

$ echo baz > foo/bar.txt

$ git add -Av
add 'foo/bar.txt'

$ git rm -rf *
rm 'foo/bar.txt'

$ git fsck
notice: HEAD points to an unborn branch (master)
Checking object directories: 100% (256/256), done.
notice: No default references
dangling blob 76018072e09c5d31c8c6e3113b8aa0fe625195ca

$ git cat-file -p 76018072e09c5d31c8c6e3113b8aa0fe625195ca
baz

no there isn't because

git rm -rf dirName

is like

rm -rf dirName

which is also irreversible but it also removes the staging files so there is no way you can get the files back. Next time use git rm --cached dirName which will only remove it from stage and not from your disc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM