正常情況下,如果所在分支有修改想工切換到其他分支就會報錯:
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 <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
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到新分支了。有誰明白也不吝賜教。