Git分支管理—解决冲突

主要步骤:

  • 在master分支上,对readme.txt文件进行最后一行的修改
  • 创建并切换到feature1分支,也对readme.txt文件进行最后一行的修改
  • 经过以上步骤,两个分支都对readme.txt文件的最后一行进行了修改
  • 然后,将feature1分支合并到master分支上,此时由于两个分支对相同的地方做了修改,无法合并发生了冲突
  • 然后我们需要到master分支下面,手动去修改冲突内容(即:删掉冲突的内容,保留一项修改)
  • 重新提交,删除feature1分支

*实战

第一步,在新的分支上做修改

准备新的feature1分支,继续我们的新分支开发:

$ git checkout -b feature1
Switched to a new branch 'feature1'```

修改readme.txt最后一行,改为:
`
Creating a new branch is quick AND simple.`

在feature1分支上提交:

$ git add readme.txt
$ git commit -m "AND simple"
[feature1 75a857c] AND simple
1 file changed, 1 insertion(+), 1 deletion(-)```

第二步,在master分支上做修改

切换到master分支:

$ git checkout master
Switched to branch 'master'
Your branch is ahead of 'origin/master' by 1 commit.
注释:Git还会自动提示我们当前master分支比远程的master分支要超前1个提交。```


在master分支上把readme.txt文件的最后一行改为:
`
Creating a new branch is quick & simple.`

提交:
```
$ git add readme.txt 
$ git commit -m "& simple"
[master 400b400] & simple
 1 file changed, 1 insertion(+), 1 deletion(-)```

现在,master分支和feature1分支各自都分别有新的提交,变成了这样:

![Paste_Image.png](http://upload-images.jianshu.io/upload_images/1803308-f1a4f91e3611f788.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

######第三步,合并两个分支
这种情况下,Git无法执行“快速合并”,只能试图把各自的修改合并起来,但这种合并就可能会有冲突,我们试试看:
```
$ git merge feature1
Auto-merging readme.txt
CONFLICT (content): Merge conflict in readme.txt
Automatic merge failed; fix conflicts and then commit the result.```
果然冲突了!Git告诉我们,readme.txt文件存在冲突,必须手动解决冲突后再提交。

进本地工作区可以直接查看readme.txt的内容:
```
Git is a distributed version control system.
Git is free software distributed under the GPL.
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```

<u>Git用`<<<<<<<`,`=======`,`>>>>>>>`标记出不同分支的内容</u>,我们修改如下后保存:
`Creating a new branch is quick and simple.`

再提交:
```
$ git add readme.txt 
$ git commit -m "conflict fixed"
[master 59bc1cb] conflict fixed```
现在,master分支和feature1分支变成了下图所示:

![Paste_Image.png](http://upload-images.jianshu.io/upload_images/1803308-3f0f1677e44ff488.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
用带参数的git log也可以看到分支的合并情况:
```
$ git log --graph --pretty=oneline --abbrev-commit
*   59bc1cb conflict fixed
|\
| * 75a857c AND simple
* | 400b400 & simple
|/
* fec145a branch test
...```

######第四步,删除feature1分支:
```
$ git branch -d feature1
Deleted branch feature1 (was 75a857c).```

***
######*完美的小结
当Git无法自动合并分支时,就必须首先解决冲突。解决冲突后,再提交,才能完成合并
用`git log --graph`命令可以看到分支合并图。

本文转自:廖大神的官方网站
http://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000/001375840202368c74be33fbd884e71b570f2cc3c0d1dcf000
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容