Git checkout to master 从另一个分支自动更新本地更改?

Git checkout to master from another branch updates automatically local changes?

我有一个空的 git 存储库,我首先在其中创建了一个内容为“pulkitsharma”的 hello.txt 文件。 在此之后,我将它添加到暂存中,然后在 master 分支中提交更改。然后我创建 另一个名为“new_branch”的分支并更新了 hello.txt 的内容 “pulkitsharma\npulkitsharma6569@gmail.com”并且没有准备提交。现在,当我 结帐到 master 分支 hello.txt 的内容会自动更新。谁能告诉 我们为什么会这样,因为我认为在结帐到 master 分支时应该有
error.Why 是 git 结账大师的输出 "M hello.txt Switched to branch 'master' "

git init
vi hello.txt
git add .
git commit -m "hello.txt added to master branch"
git checkout -b new_branch
vi  hello.txt
git checkout master

git checkout清楚:

To prepare for working on <branch>, switch to it by updating the index and the files in the working tree, and by pointing HEAD at the branch.

Local modifications to the files in the working tree are kept, so that they can be committed to the <branch>.

因此,即使您切换回 master,您对 hello.txt 的本地修改(未暂存)仍然存在。

OP 在评论中添加:

Now I accidently checkout to master branch.
Then instead of showing up error and asking of either commit or stash why does it update the files in master branch (without any extra commit in master branch)

如“”中所述,您需要:

  • 要么提交 (git commit -a -m "…") before doing git checkout master.
  • git stash 如果您不想进行“临时”提交。
    稍后,执行 git checkout new_branch && git stash pop 以检索您未提交的代码。