为什么git branch中的更改会自动复制到主分支? [重复]

时间:2020-11-29 23:46:07

This question already has an answer here:

这个问题在这里已有答案:

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:

我正在尝试使用分支来处理项目的不同部分。假设我在主分支上,我有一个文件test1。现在,我创建另一个分支并切换到它:

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:

现在我创建另一个文件,比如说test2并添加一些内容。现在当我将分支切换到主分区时,我得到:

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.

但是当我现在检查文件时,我看到文件test2包含所有内容!怎么可能?我尝试了多个分支,一切都只是被复制到所有分支。这不是我想要的,因为我想让我的实验工作与既定的工作分开。

1 个解决方案

#1


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跨分支进行未添加和未提交的更改。如果在切换分支之前不调用git commit,则会发生这种情况。所以:

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.

这是一个功能:在您提交之前,所有更改都只在工作目录中,或者在您运行git add之后,在所谓的“索引”中。索引包含未提交的更改。只有在运行git commit之后,索引的当前内容才会转换为正确的提交对象,之后索引本身将再次为空。

#1


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跨分支进行未添加和未提交的更改。如果在切换分支之前不调用git commit,则会发生这种情况。所以:

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.

这是一个功能:在您提交之前,所有更改都只在工作目录中,或者在您运行git add之后,在所谓的“索引”中。索引包含未提交的更改。只有在运行git commit之后,索引的当前内容才会转换为正确的提交对象,之后索引本身将再次为空。