Boris Stitnicky Boris Stitnicky - 3 months ago 8
Git Question

What happens to changed files when I switch Git branches?

In spite of using Git for quite some time, I still fail to understand its branching mechanics. In particular, consider a new project

foo
with a single file
bar.txt
initialized by these simple commands:

$ mkdir foo
$ cd foo
$ git init
$ touch bar.txt
$ git add .
$ git commit -m 'Initial commit'


Now when I create a branch
foobar
,
git branch
shows that I'm still on
master
:

$ git branch foobar
$ git branch
foobar
* master


But when I make change to the file
bar.txt
:

$ echo quux >> quux.txt
$ git status
modified: quux.txt


Then when I checkout the other branch, I can see that the file
bar.txt
has been modified also there:

$ git checkout foobar
$ git status
modified: quux.txt


I already know that this behavior allows me to choose to which branch do I want to commit my changes, but I find it annoying. I suspect that I fail to understand the basic idea behind Git branching. Is there a way to tell git that when I make changes to
master
, I don't want them to be visible from any other branch which I may choose to checkout?

Answer

The changes you make in the working directory aren't a part of any branch until you commit them. So where you've gone wrong is in thinking that when you checkout a branch and then modify a file, you've made a modification "on the branch". You haven't done that, you've modified the working directory.

So you have a dirty working directory based on one branch and you checkout another branch - the uncommitted changes stay in the working directory because otherwise they'd not be saved anywhere. You wouldn't be able to checkout the first branch again and have the local changes reappear.

What you probably want to do is git stash before you switch branches. This saves local changes to a temporary branch, which you can get back to later with git stash pop.