2017-03-17 49 views
0

我對git分支行爲感到困惑。代碼更改是否應該在不同分支間持續存在?

我有這個混帳回購協議:

$ git status 
On branch master 
Your branch is up-to-date with 'origin/master'. 
nothing to commit, working tree clean 

我創建一個本地分支,像這樣:

$ git checkout -b foo 
Switched to a new branch 'foo' 
$ git branch 
* foo 
    master 
$ git status 
On branch foo 
nothing to commit, working tree clean 

現在我改變README.md文件。

$ date >> README.md 
$ git status 
On branch foo 
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: README.md 

no changes added to commit (use "git add" and/or "git commit -a") 

現在我跳回到我的主分支,像這樣:

$ git checkout master 
M README.md 
Switched to branch 'master' 
Your branch is up-to-date with 'origin/master'. 

但是當我做了git的狀態我看到README.md文件已經從我的富分支的修改!我不應該看到README.md文件的未修改版本嗎?我在這裏做錯了什麼?

$ git status 
On branch master 
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: README.md 


no changes added to commit (use "git add" and/or "git commit -a") 
$ tail README.md 
# README.md 
----------- 

Meanvoy is just an idea I had to replace envoy with facter and 
a mean stack backend. 
Fri Mar 17 13:43:04 PDT 2017 
+1

您沒有將自述文件提交到您的分支,也沒有將其分級。你需要在分支上加上'git add '和'git commit'來永久保存它。 –

+0

啊!這確實有我正在尋找的效果。我只是不想在我的foo分支中做任何永久的事情。謝謝。 –

回答

3

讓我們首先對第二考慮當你檢出不同的分支發生了什麼,並且不能修改任何文件

當你這樣做時,git會首先將HEAD移動到歷史上這個其他分支的新位置,然後git會根據這個其他分支更新你的工作文件夾以包含所有文件的狀態。

因此,例如,如果您簽出一個功能分支,您的工作文件夾將被更新以反映該功能分支的當前狀態。目前聽起來不錯?好。

現在,如果在檢出其他分支之前修改文件,會發生什麼?

那麼,除非明確告知,否則git會盡量避免丟失您的更改。那麼它應該怎麼做?拒絕結帳這個其他分支,因爲你已經修改了一些文件但沒有提交他們

不,git將改爲嘗試帶來改變。

它只會這樣做,如果這樣做是安全的。如果文件的兩個分支之間的分歧,git會沿的

$ git checkout feature/x 
error: Your local changes to the following files would be overwritten by checkout: 
     test1.txt 
Please commit your changes or stash them before you switch branches. 
Aborting 

事實行的錯誤拒絕,這並不意味着該文件是「安全的」一起帶入這個新的分支。仍然修改。仍然未提交。

您將不得不決定如何處理文件。如果您希望它在前一個分支上「保持」,那麼您在檢出新分支之前應該已經提交

相關問題