How do I create a git branch so that files I add to it are not added to master?
题
I want to create a git branch that will work independent of the master branch. I want all the code that is present in the master till now, but any further changes in the master should not reflect in the branch and any changes in the branch should not reflect in the master.
I used this command to create branch:
git branch test
But any file I add in master
, I can see in test
. And any new file added in test
, I can see in master
. How to avoid this? I did not use any --track option while creating the branch.
解决方案
What you've asked for is exactly what git branch test
does (a point from which the two histories are no longer shared). There is two levels of confusion here though:
When you
git add newfile
, you are adding it to the index, but not committing it or updating any branch with it's contents. When you check out a new branch then, as long as there is no conflict, git will not reset those changes from the index. This is a desirable behavior, for example if you are working on another branch and want to take only a subset of the uncommitted changes over to another branch. If yougit commit
the state of the index on your original branch, the index won't retain those changes when you go back to the test branch.When you move between trees that have new files added or removed, a
git checkout
will not necessarily remove them from the filesystem (if there is a reset operation). Then you may "see" these files when you switch branches, e.g. in the output ofls
orgit status
-- but they are "untracked" and git will not try to do anything with them (git commit -a
, for example, will not add this file to the index before writing a new tree). This is nothing to worry about, but if you're OCD about it, you can delete them (or usegit clean
).
其他提示
I think what you wanted was:
git checkout --orphan somebranch
this will create a somebranch
with no history whatsoever, you can add which files you want to that one, and they might differ 100% from your previous branches.
git branch test
git add .
git checkout test
git checkout master
As long as you don't commit, you will see your working tree and your index (which references what you have added) in both branches test
and master
.
git checkout test
git commit -m "files for test"
git checkout master
Then you won't see in master
the files you have just committed in test
.
You new branch test
will have recording a new commit (with new content), independent from master
.