7

I accidentaly deleted local file changes on git repository. They were NOT commited or even pushed.

What I did: git status (then files not staged for commit showed and I accidentaly removed whole folder called "smdr" by this comand): git checkout -- smdr

Then files changes disappeared.

How can I recover those files (birng everything back before that git checkout -- smdr comand)?

Zoe
  • 27,060
  • 21
  • 118
  • 148
  • If they weren't committed, your best bet is to check the Trash or Recycle Bin on whatever computer the local files were on. If you're using Windows, there's a "Previous versions" you can revert back to in the properties of the folder (if you have this feature on) – Avantol13 Jun 04 '15 at 12:03
  • @Avantol13 when you delete something in the cli, you usually never can find them back in the trash – edi9999 Jun 04 '15 at 14:52
  • it happened to me the same... you might find this discussion useful https://stackoverflow.com/questions/1836742/using-git-how-do-i-ignore-a-file-in-one-branch-but-have-it-committed-in-another – jjrr Oct 18 '22 at 13:50

3 Answers3

14

You can't with Git. The files were not committed so they are not in history. You just got the (inexistant) version in the index with git checkout.

Your only hope is your backup system.

Matthieu Moy
  • 15,151
  • 5
  • 38
  • 65
  • 1
    If you previously stashed (and dropped), and you know the content would've been part of the stash. Then try to recover the stash. That way it would be possible to at least partially recover the files affected by `git checkout`. – vallentin Sep 03 '19 at 18:43
6

You can use any of the given options:

Git reflog

Type git reflog and checkout the commit you need, it will "revert" your repository to the "deleted" commit.

Git revert

Another option is use git revert SHA-1 which will revert your commit. It will simply undo your changes

Git reset

Git reset will checkout the content of the given sha-1. It will set your branch to be at the same state as the SHA-1

Community
  • 1
  • 1
CodeWizard
  • 128,036
  • 21
  • 144
  • 167
1

In addition to the accepted answer, I found this good practice we can follow to prevent checkout accidents from happening again.

This stuck out most to me from this answer.

"Here's another crazy idea: don't run 'git checkout ...' on a dirty work tree. Problem solved."

I stopped ever since using git checkout . to discard any unstaged/uncommitted changes. I now use the command which was made to be more suitable for this: git reset.

git reset and git reset --hard when you're absolutely sure you want to discard your changes permanently. git stash is also your friend, just before you discard those changes, doesn't hurt to stash it before you delete. Making these two a habit and using git checkout only for switching between branches (mostly) works really well for me.

joeljpa
  • 317
  • 2
  • 13