git - 在 git 中切换分支 - 我什么时候会得到 "You have local changes cannot switch branches."?

标签 git branch git-branch git-checkout

<分区>

Possible Duplicates:
git: Switch branch and ignore any changes without committing.
Git branches behaving strangely

我知道一般建议是在 git 中切换分支之前保持干净状态。 ( stash 或 park-commit )。我试图了解我什么时候会得到“你有本地更改不能切换分支”,我无法遵循逻辑:

我有一个 repo,有一个名为 version.txt 的文件,包含文本“1”:

git checkout -b new

echo 2 >> version.txt (working dir is not dirty, modified the file)

git checkout master ( how come this works ? I have not stages\commited my changes on new )

如果我删除新分支中的文件内容,或者先暂存文件,也会发生同样的情况。

有人可以帮助我了解我什么时候会收到“您有本地更改无法切换分支。” ?

谢谢, 冉

最佳答案

这很简单,如果您更改了一个文件,如果您更改到特定分支,该文件将被修改。

例子:

$ git init
Initialized empty Git repository in /tmp/asadfasd/.git/
$ echo 1 > bar
$ git commit -am "commit 1 master"
[master (root-commit) 55da003] commit 1
 1 files changed, 1 insertions(+), 0 deletions(-)
 create mode 100644 bar
$ git co -b testbranch
Switched to a new branch 'testbranch'
$ git co master
Switched to branch 'master'
$ echo 2 >> bar
$ git commit -am "commit 2 master"
[master c6dc6d9] commit 2 master
 1 files changed, 1 insertions(+), 0 deletions(-)
$ git co testbranch
Switched to branch 'testbranch'
$ echo 3 >> bar
$ git co master
error: Your local changes to the following files would be overwritten by checkout:
bar
Please, commit your changes or stash them before you can switch branches.
Aborting

如果您在修改文件之前将 testbranch rebase 到 master 上,它将起作用,因为文件不会被修改。

换句话说,如果分支是 fork 的,而你修改 fork 的文件,它将无法工作。

关于git - 在 git 中切换分支 - 我什么时候会得到 "You have local changes cannot switch branches."?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6638937/

相关文章:

linux - 如何在 Ubuntu 20.04 中安装 Git

git - 从更新的基本分支获取更改到我的功能分支

GIT - 如何知道分支分支的分支?

哈希上的 Ruby case 语句?

command-line - 漂亮的hg分支图

git - 为什么分支名称不能包含 'space' 字符?

git - 有没有办法制作 PR 但在我的 github 帐户中将 repo 设为私有(private)?

git - 将远程master分支 merge 到本地分支(master除外)的方法

Github 切换 fork 父级

git - 我如何将两个(或更多)完全不相关的线性分支祖先 "splice"变成一个新的?