1

I am trying to use branches to work on different parts of my project. Let's say I am on the master branch and I have a file test1 on it. Now, I create another branch and switch to it:

git branch first_branch
git checkout first_branch

Now I create another file, say test2 and add some content to it. Now when I switch branch to master, I get:

Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.

But when I check the files now, I see the file test2 with all the contents! How is that possible? I tried with multiple branches and everything simply gets copied across all the branches. This is not what I want since I want to keep my experimental work separate from an established work.

James Z
  • 12,209
  • 10
  • 24
  • 44
Peaceful
  • 4,920
  • 15
  • 54
  • 79

1 Answers1

1

This is working as intended. git checkout takes un-added and un-committed changes across branches. This will happen if you do not call git commit before switching branches. So:

git checkout master ; git checkout -b first_branch
# modify test1
git add test1
git checkout master
# test1 still modified
git checkout -b second_branch
# test1 still modified

This is a feature: until you commit, all your changes are either only in the working directory, or, after you run git add, in the so-called "index". The index contains non-committed changes. Only after you run git commit, the current content of the index is converted into a proper commit object, after which the index itself will be empty again.

AnoE
  • 8,048
  • 1
  • 21
  • 36