正常情况下,如果所在分支有修改想工切换到其他分支就会报错:
zhangjie$ git checkout mastern
error: Your local changes to the following files would be overwritten by checkout:
first
Please commit your changes or stash them before you can switch branches.
Aborting
比如我有如下文件
zhangjie$ ls
README.md first mn
zhangjie$ git diff
diff --git a/first b/first
index 9465807..f9c4725 100644
--- a/first
+++ b/first
@@ -1,4 +1,3 @@
-it i
oi
我的分支为
git branch
masn
* master
mastern
mn
从上面可看出我有一个分支名为mn,也有一个文件名为mn,此时我也有修改,我执行checkout
zhangjie$ git checkout mn
M first
Switched to branch 'mn'
Your branch is up-to-date with 'origin/master'.
zhangjiedeMacBook-Pro:gitLearning zhangjie$ git status
On branch mn
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
(use "git add
(use "git checkout --
modified: first
no changes added to commit (use "git add" and/or "git commit -a")
zhangjiedeMacBook-Pro:gitLearning zhangjie$ git diff
diff --git a/first b/first
index 9465807..f9c4725 100644
--- a/first
+++ b/first
@@ -1,4 +1,3 @@
-it i
oi
可以看到我在master里的修改没有提交,没有stash,但是我checkout 到了mn这个分支,并且把在master的修改带过来了。
我在mn分支提交后再切回到master,master里没有修改了
zhangjiedeMacBook-Pro:gitLearning zhangjie$ git commit -m 'd ling'
[mn 317c0c3] d ling
1 file changed, 1 deletion(-)
zhangjiedeMacBook-Pro:gitLearning zhangjie$ git checkout master
Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.
zhangjiedeMacBook-Pro:gitLearning zhangjie$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working directory clean
zhangjiedeMacBook-Pro:gitLearning zhangjie$
比较奇妙,不仅在有修改的时候能切换分支,且可以把修改的内容merge过去,感觉是因为分支名和文件名相同,被认为是checkout file,但实际执行的却是checkout branch,但是如果到新的分支,原来的内容就丢失了,所以就把原分支的修改merge到新分支了。有谁明白也不吝赐教。