在上一节中, 我们做了一个合并分支的操作 .但是, 在合并分支的时候, 往往是会发生一些冲突的 , 这时候我们就需要解决这些冲突 !

我们在demo 上创建新的feature1分支 :

$ git checkout -b feature1

切换到一个新分支 'feature1'

修改readme.txt最后一行,改为:

Creating a new branch is quick AND simple.

接着在feature1分支上提交:

$ git add readme.txt 
$ git commit -m "AND simple"

[feature1 73a4900] AND simple
 1 file changed, 1 insertion(+), 1 deletion(-)

切换到master分支:

$ git checkout master

现在, 我们再在master分支上把readme.txt文件的最后一行改为:

Creating a new branch is quick & simple.

提交 :

$ git add readme.txt 
$ git commit -m "& simple"

现在,master分支和feature1分支各自都分别有新的提交

在这种情况下,Git是无法执行“快速合并”的,只能试图把各自的修改合并起来,但这种合并就可能会有冲突,我们合并一下看看:

$ git merge feature1

会提示冲突 :

自动合并 readme.txt
冲突(内容):合并冲突于 readme.txt
自动合并失败,修正冲突然后提交修正的结果。

所以, 我们需要去手动解决冲突 , 我们使用 git status 命令看看发生冲突的文件 , 会出现下面这样的提示 :

$ git status
位于分支 master
您有尚未合并的路径。
  (解决冲突并运行 "git commit")

未合并的路径:
  (使用 "git add <文件>..." 标记解决方案)

    双方修改:     readme.txt

修改尚未加入提交(使用 "git add" 和/或 "git commit -a")

现在我们打开 readme.txt 文件, 会发现内容变成了下面这个样子 :

Git is a distributed version control system.
Git is free software.
Git has a mutable index called stage.
Git tracks changes of files.
<<<<<<< HEAD
Creating a new branch is quick & simple.
=======
Creating a new branch is quick AND simple.
>>>>>>> feature1

Git会用<<<<<<<=======>>>>>>>标记出不同分支的内容

现在我们把冲突的内容修改成 :

Creating a new branch is quick and simple.

再提交 :

$ git add readme.txt 
$ git commit -m "conflict fixed"
[master c77e828] conflict fixed

现在,master分支和feature1分支变成了下图所示:

我们也可以用带参数的git log看到分支的合并情况:

$ git log --graph --pretty=oneline --abbrev-commit

会显示 :

commit
*   c77e828 conflict fixed
|\  
| * f64e72b AND simple
* | 9d27459 & simple
|/  
* 2b76425 readme.txt

最后,我们删除feature1分支:

$ git branch -d feature1

results matching ""

    No results matching ""