Accidently removed files from local folder after running "git checkout origin/main"

Viewed 49

I am new to git.

I accidentally deleted all project files from my local machines after running git checkout origin/main command.

I have checked and could not find the files in the Recycle bin as well. How can I recover those lost files?

I was following a script that I have written when I was learning Git and this was the first time that I tried it on an actual project. Following is the message I receive. Should I run git switch. If yes, how.

Message received after running the checkout command

I do not want to do something stupid again and loose whatever I am left with. How can I recover those lost files?

3 Answers

Yes, say git switch - and see if all the files return. I think they will.

I don't think the files were ever deleted. You need to understand that the project files you see are not the real project files. The real files are hidden in the real Git repository, which is invisible.

I accidentally deleted all project files from my local machines after running git checkout origin/main command.

I don't think so. I think you just did a checkout of a different branch — to a branch where those files don't exist. You need to understand what branches are.

The good new is : the command your ran isn't a destructive command, you simply have switched from your initial commit to the commit currently at origin/main.


The shortest way to get back to where you were before is to run :

git switch -

(in that command: - means "the state I was in previously")

A more detailed way is to run git reflog, inspect the history of actions you did, and return to either a specific sha1 or to a branch because the associated message mentions : checkout: moving from <branch> to origin/main.

(actually: git switch - is a shortcut to "inspect the reflog and go back to the last time it mentions 'moving from this to that'")

git checkout can be dangerous because it operates both on files and branches.

That is why Git 2.23+ (Q3 2019) has introduced git switch (man page)

It would not switch if the working tree had files which would be removed or modified. If your have disappeared, it means they were committed.

- is a shorthand for @{-1} which is specified in gitrevisions:

The construct @{-<n>} means the <n>th branch/commit checked out before the current one.

Related