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

Why are changes in git branch are getting copied to the main branch automatically?

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

git branch first_branch
git checkout first_branch

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

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

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

这是按预期工作的。 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

这是一项功能:在您提交之前,您的所有更改要么仅在工作目录中,要么在您 运行 git add 之后,在所谓的 "index" 中.索引包含未提交的更改。只有在你 运行 git commit 之后,索引的当前内容被转换为适当的提交对象,之后索引本身将再次为空。