Reputation: 6781
I have been studying from the book ProGit, and stumbled upon this paragraph under the topic "Reset Demystified":
Switching branches or cloning goes through a similar process. When you checkout a branch, it changes HEAD to point to the new branch ref, populates your Index with the snapshot of that commit, then copies the contents of the Index into your Working Directory.
However, as you can see in the below terminal output, I am unable to replicate the behavior.
GaurangTandon@Gaurang MINGW64 /j/test (master)
$ git status
On branch master
nothing to commit, working tree clean
GaurangTandon@Gaurang MINGW64 /j/test (master)
$ touch a.txt
GaurangTandon@Gaurang MINGW64 /j/test (master)
$ git checkout -b "dev"
Switched to a new branch 'dev'
GaurangTandon@Gaurang MINGW64 /j/test (dev)
$ git status
On branch dev
Untracked files:
(use "git add <file>..." to include in what will be committed)
a.txt
nothing added to commit but untracked files present (use "git add" to track)
According to me, based on my interpretation of that paragraph: after I checked out to
the new branch dev
, Git should have populated the Index with the snapshot of the commit master
was at (since both dev
and master
point to the same commit, as I verified on Visualizing Git). That commit should not have had the file a.txt
, as it was created after the commit. Also, my working directory should have had the same contents as the Index, i.e., without the file a.txt
.
Yet, as you can see in the output above, my working directory happens to have the file a.txt
, and it is detected by git status
.
I wish to understand where I have made a mistake in interpreting the paragraph.
Upvotes: 0
Views: 420
Reputation: 1042
This is the normal behaviour of git checkout
: as stated in the documentation :
Local modifications to the files in the working tree are kept, so that they can be committed to the
branch
.
Upvotes: 1
Reputation: 522752
As far as I know, Git checkout will carry over modified files in your working directory when switching branches. The documentation supports this claim:
git checkout <branch>
To prepare for working on <branch>, switch to it by updating the index and the files in the working tree, and by pointing HEAD at the branch. Local modifications to the files in the working tree are kept, so that they can be committed to the <branch>.
As to why Git might have this behavior, this prevents accidentally wiping out changes in the working directory by changing branches.
Upvotes: 1