Boris Stitnicky Boris Stitnicky - 2 months ago 5x
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

with a single file
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
git branch
shows that I'm still on

$ git branch foobar
$ git branch
* master

But when I make change to the file

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

Then when I checkout the other branch, I can see that the file
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
, I don't want them to be visible from any other branch which I may choose to checkout?


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.