Git: deleted a bunch of files accidentally from a repository, how to get them back?
You know the the horrible, sinking feeling, when you accidentally wiped out half of the repo with a harmless looking rm -rf. No worried though, you can get all back if it's a Git repo.
Deleted – nothing else after that
Just deletion, and no staging or nothing after that. Checkout should do the trick:
$ git checkout .
Deleted – added to the staging area
File got deleted and then added to the staging area, at this point you noticed that something’s wrong:
# Reset the head first $ git reset HEAD <file> # Then checkout $ git checkout <file> # Or if it's a ton of files, then use the dot $ git reset HEAD . $ git checkout .
Deleted — added, and committed
If you went the whole way and committed all the deletions, then rollback with
RESET to the last commit. The following will roll back 1 commit:
$ git reset --hard HEAD~1
Or rollback to s specific commit ID:
$ git reset --hard 80789fa6a027b3ee3dec760e5784c61b7e4c9d17
git log for commit IDs.
It’s a bit like when rock climbing a massive wall (I don’t do that, just heard stories), you’re good if you just remember to set a stopper, the robe will catch you if you fall. But sometimes, you’re so into the climbing that you forget to do that, and notice that it’s been like 25 meters without, that means 50 meter drop (swallows in horror). Git commits are like those stoppers, do them often and you’re good.
It’s really hard to delete anything permanently in Git, in that it’s an excellent program!
Also, see this nice thread on the dangers of
rm and how to safeguard yourself from yourself.