Git: deleted a bunch of files accidentally, how to get them back?

You know the sinking feeling when you accidentally wipe out half of the repo with a harmless-looking rm -rf. Don't worry, though. There’s a good chance of getting it back.

Deleted – nothing else after that

Just deletion, with no staging or other changes afterward. 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. The reset step is also explained in the guide to removing files from Git's staging area:

# 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 roll back to a specific commit ID:

$ git reset --hard 80789fa6a027b3ee3dec760e5784c61b7e4c9d17

Get the commit ID with git log.

Takeaways

It’s relatively hard to delete anything permanently in Git.

Also, see this nice thread on the dangers of rm and how to safeguard yourself from yourself.