1

I initialize a new repository in an empty folder:

git init

Now I copy two files A.java and B.java into this folder and commit:

git add A.java B.java && git commit -m "Added A.java and B.java to repo"

Next I create a new branch:

git branch newBranch

Afterwards I rename B.java to C.java (intentionally not using mv) and commit on the master branch. For git it is a deletion of B.java and a creation of C.java:

git add C.java && git commit -m "Renamed B.java to C.java"

Follow on I wanna switch to my newly created branch:

git checkout newBranch

When I take a look on my working directory now B.java will be gone and only A.java exists. Why? I did the branch before the second commit. I would expect that A.java and B.java are in their original state as when I executed the branch command. But obviously they are not and I don't understand why. Why is B.java gone?

user73347
  • 47
  • 3

1 Answers1

1

A git status should confirm it, but when you created your third commit, you only registered the creation of C.java.
You would have needed git add B.java to record the deletion of B.java from the history.

Since you did not, B.java remained deleted in the working tree.

Which means, switching to newBranch keep the working tree as is, with B.java deleted.

You can restore it with git restore B.java.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • I still don't get it 100%. The first commit consisted of A and B. In my mind I see a snapshot on the hard drive with those two files. I understand that the deletion of B is considered a change. I did not stage this change. I only staged the new file C. For the next commit on the main branch I would expect A and B to be unchanged (since I didn't stage B) plus C. When I checkout the `newBranch` I would have expected that git takes the snapshot created first, looks into it and says "Ah, two files A and B". – user73347 Apr 27 '22 at 08:13
  • " I did not stage this change. I only staged the new file C.": that is why. Again, git status should show B as still being deleted. And changing branch would not change that. – VonC Apr 27 '22 at 09:06