'Git checkout -- recover lost files

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)?



Solution 1:[1]

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

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 joeljpa