Git合并分支出现的冲突解决

时间:2022-05-31 20:49:08

人生不如意之事十有八九,合并分支往往也不是一帆风顺的。

我们准备新的分支newbranch.

LV@LV-PC MINGW32 /c/gitskill (master)
$ git checkout -b newbranch
Switched to a new branch 'newbranch'

修改readme.txt,在最后一行添加:

$ cat readme.txt
master分支内容
添加dev分支内容
分支合并测试

在分支newbranch上提交:

LV@LV-PC MINGW32 /c/gitskill (newbranch)
$ git add readme.txt

LV@LV-PC MINGW32 /c/gitskill (newbranch)
$ git commit -m "newbranch first commit"
[newbranch cccee34] newbranch first commit
1 file changed, 2 insertions(+), 1 deletion(-)

切换到master分支上:

$ git checkout master
Switched to branch 'master'
Your branch is ahead of 'origin/master' by 2 commits.
(use "git push" to publish your local commits)

在master分支上把readme.txt文件的最后一行添加:

master分支上的合并测试内容

添加,提交

LV@LV-PC MINGW32 /c/gitskill (master)
$ git add readme.txt

LV@LV-PC MINGW32 /c/gitskill (master)
$ git commit -m "master branch merge test"
[master 4bb4c5a] master branch merge test
1 file changed, 2 insertions(+), 1 deletion(-)

这种情况下,自动合并会出现冲突:

LV@LV-PC MINGW32 /c/gitskill (master)
$ git merge newbranch
Auto-merging readme.txt
CONFLICT (content): Merge conflict in readme.txt
Automatic merge failed; fix conflicts and then commit the result.

我们直接查看合并后的readme.txt文件内容:

$ cat readme.txt
master分支内容
添加dev分支内容
<<<<<<< HEAD
master分支上的合并测试内容
=======
分支合并测试
>>>>>>> newbranch

Git会用<<<<<<<,=======,>>>>>>>标记不同分支的内容,我们修改一下后保存

master分支内容
添加dev分支内容
master分支上的合并测试内容
分支合并测试

然后添加,提交:

LV@LV-PC MINGW32 /c/gitskill (master|MERGING)
$ git add readme.txt

LV@LV-PC MINGW32 /c/gitskill (master|MERGING)
$ git commit -m "branch merge"
[master f3d8f1e] branch merge

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

LV@LV-PC MINGW32 /c/gitskill (master)
$ git log --graph --pretty=oneline --abbrev-commit
* f3d8f1e branch merge
|\
| * cccee34 newbranch first commit
* | 4bb4c5a master branch merge test
|/
* 0d0bbca dev first commit
* d5aea29 master first commit
* 023ee21 Initial commit

现在,删除newbranch分支:

LV@LV-PC MINGW32 /c/gitskill (master)
$ git branch -d newbranch
Deleted branch newbranch (was cccee34).

LV@LV-PC MINGW32 /c/gitskill (master)
$ git branch
* master

小结:当Git无法自动合并分支时,就必须首先解决冲突,解决冲突后,再提交,合并完成

可以用$ git log --graph 命令可以看到分支合并图。