Confused about a staged file that also been deleted from the working tree before commit

I’ll just say what I did:

* Created file1.txt
>git add file1.txt
* Deleted file1.txt
> git status

On branch master
No commits yet

Changes to be committed:
        new file: file1.txt
Changes not staged for commit:
        deleted: file1.txt

>git commit -m “not sure what I did here”

[master (root-commit) 594bfbb] not sure what I did here
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 file.txt

So, it looks like git has committed the staged file, which makes sense.
However, I still don’t see the file in my folder (which also makes sense).

Now, I tried to checkout the last commit and, by that, bring the file back:
> git checkout master

Already on 'master'
D New Bitmap file1.txt

I still don’t see the file in my folder. I thought by checking out the last commit (which appears to have made a Create and therfore should have my file), that I will be able to retrieve the file from the repo.

Maybe my way of getting the previous commit is wrong? Or I didn’t understand what happened to the file (was it even comitted?)

Any discussion, link or even a tip to give me some direction would be greatly appreciated!

Sorry for bumping. I am only going to do it once. 
Just thought it’s a relatively beginner topic that surely someone with more experience can help with.
Thanks anyway!

Git does its absolute best to prevent you from losing work. Let’s imagine that what you did, rather than deleting the file, was change its contents by adding hours and hours and hours of effort writing code (or whatever you produce). If that were the case, you’d be very glad that git didn’t overwrite your work :grinning:

So, as you’ve noticed, git has three main places where it stores information: the “working directory”, the “index”, and the repository itself. When you stage a change, it is stored in the index. When you commit a change, it takes the contents of the index, creates a commit from it, and stores it in the repository.

What you want to do in the case of your particular situation is force the working directory to match the contents of the repository at the latest commit. This can be done using either of the following commands:

git reset --hard HEAD

git restore --source HEAD .

The git restore command is new in git v2.23, but it (along with git switch) is meant to fix a few long-standing problems with the discoverability and usability of some common commands … like this one :grinning:

Let us know if you have more questions.

2 Likes